如何在C中四舍五入浮点值(如37.777779)到小数点后两位(37.78)?
当前回答
你仍然可以使用:
float ceilf(float x); // don't forget #include <math.h> and link with -lm.
例子:
float valueToRound = 37.777779;
float roundedValue = ceilf(valueToRound * 100) / 100;
其他回答
...或者你也可以采用传统的方式,不需要任何库:
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;
当然,如果你想从数字中去除额外的信息。
在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个变量,但我把它们留在那里,这样你就可以看到逻辑。可能有更简单的解决方案,但这对我来说很有效——特别是因为它允许我根据需要调整小数点后的位数。
使用%。printf中的2f。它只打印2个小数点。
例子:
printf("%.2f", 37.777779);
输出:
37.77
这个宏用于浮点数四舍五入。 把它添加到你的头文件中
#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);