C/C++ 浮點數[精度問題]~四捨五入函數
C/C++ 浮點數[精度問題]~四捨五入函數
// 四捨五入 取到 小數點第 X 位
double CLib::rounding(double num, int index)
{
//https://dotblogs.com.tw/forloop/2016/07/31/rounding
bool isNegative = false; // whether is negative number or not
if(num < 0) // if this number is negative, then convert to positive number
{
isNegative = true;
num = -num;
}
if(index >= 0)
{
int multiplier;
multiplier = pow(10, index);
num = (int)(num * multiplier + 0.5) / (multiplier * 1.0);
}
if(isNegative) // if this number is negative, then convert to negative number
{
num = -num;
}
return num;
}