string转double后,因为精度问题的解决方法

常见问题:string转double后,因为精度问题,导致对double进行四舍五入的时候不精确的问题,找到一个比较好的方法。方法见FormatDecimal。调用示例见最底部。

错误方法:string (“442477.876106195”)=> double(442477.87610619498)=> 保留8位小数结果为 (442477.87610619),实际结果应该为(442477.87610620)
正确方法:string (“442477.876106195”)=> double(442477.87610619498)=> FormatDecimal方法处理后结果为(442477.87610619998)=> 保留8位小数结果为(442477.87610620
 
 
 
/*
* 函数名称: FormatDecimal
* 函数功能: 提高double四舍五入前数据的精度
* 参    数:
* dblValue   原始double数据
* nDecimal  四舍五入的位数
* 返 回 值: 四舍五入前的double数据
* 示    例: FormatDecimal(442477.87610619498, 8)=442477.87610619998
*/
double FormatDecimal(double dblValue, int nDecimal)
{
double dRetval;
double dMod = 0.0000001;
if (dblValue < 0.0) dMod = -0.0000001;
dRetval = dblValue;
dRetval += (5.0 / pow(10.0, nDecimal + 1.0));
dRetval *= pow(10.0, nDecimal);
dRetval = floor(dRetval + dMod);
dRetval /= pow(10.0, nDecimal);
return(dRetval);
}

 
 
调用示例:
fReturn = _tstof(strReturn.c_str());
fReturn = FormatDecimal(fReturn, iDotnum);
std::stringstream buffer;
buffer << std::fixed << std::setprecision(iDotnum) << fReturn;
strReturn.assign(buffer.str());
posted @ 2022-04-21 13:24  、有妖气  阅读(1867)  评论(0编辑  收藏  举报