我们知道,计算机中double, float类型的数据常常需要你去确定到底四舍五入到小数点后的几位. 所以, 我专门写了一个函数来完成这个功能.
注意,下面我以保留小数点后两位来说明.如果想保留三位,四位......可以依此类推
//
//Here I analyze if the double data should be carry.
//For example, 8.494 should convert to 8.49. 8.495 should be 8.50.
//
double RoundData(double d)
{
double dt = d * 100;
double dCeilResult = ceil(dt);
double df = dCeilResult - dt - 0.5f;
if(df > 0.05)
return floor(dt)/100.0; //Get the max int data that is less than variable "dt".
else if (df < -0.05)
return dCeilResult/100.0; //Get the minor int data that more than variable "dt".
else if (d > 0)
return dCeilResult/100.0; //If it is positive number, get the minor int data that more than variable "dt".
else
return floor(dt)/100.0; //If it is negative number, get the max int data that is less than variable "dt".
}
本文介绍了一个自定义函数,用于将double类型的数值精确到小数点后指定位数并进行四舍五入处理。通过示例展示了如何确保数值如8.494被正确处理为8.49,而8.495则处理为8.50。
2459

被折叠的 条评论
为什么被折叠?



