C++数据精度问题(对浮点数保存指定位小数)
1、背景
对浮点数保存指定位小数。比如,1.123456.要保存1位小数,,调用方法后,保存的结果为:1.1。再比如,1.98765,保存2位小数的结果为:2.00.
2、解决方案
A、添加头文件
#include#include
B、添加命名空间
usingnamespacestd;
C、添加函数
/*函数名:round /*函数功能:数据精度计算函数 /*函数参数:floatsrc:待求精度数intbits:精度(0表示保留小数点后0位小数,1表示保留1位小数,2:表示保留2位小数) /*函数返回值:精度求取结果 /*Author:Lee /************************************************************************/ floatround(floatsrc,intbits);
函数实现
floatCDemo1Dlg::round(floatsrc,intbits) { stringstreamss; ss<>f; returnf; }
D、调用方式
CStringstr2=L"99.054"; floatf2=(float)_wtof(str2); f2*=10; f2=this->round(f2,2);
E、注意
比如,1.05,double在计算机中表示为1.0499999997,float表示为1.0500000003,但其实际都是与1.05相等的。
round方方式对处理的位数为5的情况有例外,比如:1.05,处理的结果可能为1.0499999997。这里写的是float,你可以换做其他的类型。自己多测几次就明白了