double或者float类型数据怎样保留小数点

如题所述

方法一:
                利用c++中的 cmath库中的函数:举例说明保留两位小数:double pi = 3.1415926; round(pi*100)/100;
这个方法比较好用使用,但是如果使用to_string();函数进行转换为std::string类型,则会添加0补全小数
点以后的六位,引出了方法二。
方法二:
直接上代码:
            
[cpp] view plain copy print?
<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;  
    }  
      
}  

             具体的不在解释,网上还有很多的方法来保留小数点位数,不在列举;欢迎大家批评指点。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-11-08
printf时直接%.1f就是保留一位小数
例如:
printf("%.3f",x); //保留了3位小数本回答被网友采纳
相似回答