------ 更新日期 2018年5月13日 21:41:46
1、背景
对浮点数保存指定位小数。比如, 1.123456. 要保存1位小数,,调用方法后, 保存的结果为: 1.1。 再比如,1.98765, 保存2位小数的结果为: 2.00.
2、 解决方案
A、添加头文件
#include <sstream>
#include <iomanip>
B、添加命名空间
using namespace std;
C、添加函数
/************************************************************************/
/* 函数名:round
/* 函数功能:数据精度计算函数
/* 函数参数:float src:待求精度数 int bits:精度(0表示保留小数点后0位小数,1表示保留1位小数,2:表示保留2位小数)
/* 函数返回值:精度求取结果
/* Author: Lee
/************************************************************************/
float round(float src, int bits);
函数实现
float CDemo1Dlg::round(float src, int bits)
{
stringstream ss;
ss << fixed << setprecision(bits) << f;
ss >> f;
return f;
}
D、调用方式
CString str2 = L"99.054";
float f2 = (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, 你可以换做其他的类型。自己多测几次就明白了
// 最近采用的方法,, 可行, 实际中已经用过了
主要是在内存中用到的变量, 最近就遇到了, 130.34. 而内存中 用double 保存的结果为 130.399999999, 导致后面使用的过程中出现了问题。不能精确为 130.34。 新采用的方法如下:
// 包含头文件
#include <math.h>
// 功能:四舍五入(double),支持正负数
// dSrc : 待四舍五入之数
// iBit : 保留的小数位数。 0 - 不保留小数、1 - 保留一位小数
// 返回值:返回计算结果
//
double Round(_In_ double dSrc, _In_ int iBit)
{
double retVal = 0.0;
int intTmp = 0;
// 若保留小数位数不正确
if ( 0 > iBit )
{
return 0;
}
// 若 为负数
if (0 > dSrc)
{
// 首先转为正数
dSrc *= -1;
intTmp = (int)((dSrc + 0.5 / pow(10.0, iBit)) * pow(10.0, iBit));
retVal = (double)intTmp / pow(10.0, iBit);
// 再转为 负数
retVal *= -1;
}
// 若为非负数
else
{
intTmp = (int)((dSrc + 0.5 / pow(10.0, iBit)) * pow(10.0, iBit));
retVal = (double)intTmp / pow(10.0, iBit);
}
// 返回计算结果
return retVal;
}
//---------- 2018-10-25 14:03 更新--------------- 增加函数模版(图片)-------------
float 数据类型测试: 需要得到 35.57, 数据源是:35.569999999