1. 程式人生 > >double或者float型別資料怎樣保留小數點

double或者float型別資料怎樣保留小數點

                            關於浮點型資料怎樣保留小數位

方法一:                 利用c++中的 cmath庫中的函式:舉例說明保留兩位小數:double pi = 3.1415926; round(pi*100)/100; 這個方法比較好用使用,但是如果使用to_string();函式進行轉換為std::string型別,則會新增0補全小數 點以後的六位,引出了方法二。 方法二: 直接上程式碼:
 <pre name="code" class="html">double c = (double)a / b;
	string dd = to_string((double)100.00*a/b);//將數字裝換為字串  
	string desData = "";//目標字串 用來存放保留兩位小數的字串---3.14  
	bool is_dot = false;
	int m = 0;
	for (int i = 0; i<strlen(dd.c_str()); i++) {//整個for迴圈是利用Asscii值來判定小數點位數後兩位的  
		int j = 0;
		
		
		if (dd.c_str()[i] == 46) {
			is_dot = true;
			m = i;
		}
		cout << "m is:" <<m<<endl;
		desData += dd.c_str()[i];
		if (is_dot && (i - m == 2)) {
			cout << desData << endl;
			break;
		}
		
	}

             具體的不在解釋,網上還有很多的方法來保留小數點位數,不在列舉;歡迎大家批評指點。