主要思想是把原来的double数据扩大到精度位数的值,然后加上0.5,得到四舍五入的数据,、最后再缩小回按精度位处理的数据。
代码实现如下:
double Power(int iBase, int iPower)
{
double dRet = 1.0;
for(int i = 0; i < iPower; i++)
{
dRet *= iBase;
}
return dRet;
}
double DealDoublePrecision(double dVal, int iPrecision)
{
return (int)(dVal * Power(10, iPrecision) + 0.5) / Power(10, iPrecision);
}
调用时:
double dVal = 12.890765006;
dVal = test.DoublePrecisionDeal(dVal, 4);
精度为4时输出12.8908;
精度为2时输出12.89;
精度为5时输出12.89077;
还有一种方法,用sprintf和sscanf实现
double DoubleRound(double dValue, unsigned int nPrecision)
{
char szValue[20] = {0};
double dRetVal = 0.0;
sprintf(szValue, "%.*lf", nPrecision, dValue);
sscanf(szValue, "%lf", &dRetVal);
return dRetVal;
}
还有一种是用输入输出流的方式:
#include <iostream>
#include <sstream>
#include <iomanip>
double DoubleRoundFunction(double dVal, int iPrecision)
{
std::stringstream ss;
ss << std::fixed << std::setprecision(iPrecision) << dVal;
ss >> dVal;
return dVal;
}