如何在C中四舍五入浮点值(如37.777779)到小数点后两位(37.78)?


当前回答

此函数接受数字和精度,并返回四舍五入后的数字

float roundoff(float num,int precision)
{
      int temp=(int )(num*pow(10,precision));
      int num1=num*pow(10,precision+1);
      temp*=10;
      temp+=5;
      if(num1>=temp)
              num1+=10;
      num1/=10;
      num1*=10;
      num=num1/pow(10,precision+1);
      return num;
}

它通过左移浮点数并检查大于5的条件将浮点数转换为int。

其他回答

...或者你也可以采用传统的方式,不需要任何库:

float a = 37.777779;

int b = a; // b = 37    
float c = a - b; // c = 0.777779   
c *= 100; // c = 77.777863   
int d = c; // d = 77;    
a = b + d / (float)100; // a = 37.770000;

当然,如果你想从数字中去除额外的信息。

没有办法将一个浮点数四舍五入为另一个浮点数,因为四舍五入的浮点数可能不可表示(浮点数的限制)。例如,假设你将37.777779四舍五入为37.78,但最接近的数字是37.781。

然而,你可以使用格式化字符串函数来“舍入”浮点数。

在c++中(或在带有C风格强制类型转换的C中),您可以创建以下函数:

/* Function to control # of decimal places to be output for x */
double showDecimals(const double& x, const int& numDecimals) {
    int y=x;
    double z=x-y;
    double m=pow(10,numDecimals);
    double q=z*m;
    double r=round(q);

    return static_cast<double>(y)+(1.0/m)*r;
}

然后std::cout << showDecimals(37.777779,2);结果是:37.78。

显然,你不需要在函数中创建所有5个变量,但我把它们留在那里,这样你就可以看到逻辑。可能有更简单的解决方案,但这对我来说很有效——特别是因为它允许我根据需要调整小数点后的位数。

这个宏用于浮点数四舍五入。 把它添加到你的头文件中

#define ROUNDF(f, c) (((float)((int)((f) * (c))) / (c)))

这里有一个例子:

float x = ROUNDF(3.141592, 100)

X = 3.14:)

printf("%.2f", 37.777779);

如果你想写入C-string:

char number[24]; // dummy size, you should take care of the size!
sprintf(number, "%.2f", 37.777779);