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


当前回答

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

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

这里有一个例子:

float x = ROUNDF(3.141592, 100)

X = 3.14:)

其他回答

代码定义:

#define roundz(x,d) ((floor(((x)*pow(10,d))+.5))/pow(10,d))

结果:

a = 8.000000
sqrt(a) = r = 2.828427
roundz(r,2) = 2.830000
roundz(r,3) = 2.828000
roundz(r,5) = 2.828430

你仍然可以使用:

float ceilf(float x); // don't forget #include <math.h> and link with -lm.

例子:

float valueToRound = 37.777779;
float roundedValue = ceilf(valueToRound * 100) / 100;

使用%。printf中的2f。它只打印2个小数点。

例子:

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

输出:

37.77
double f_round(double dval, int n)
{
    char l_fmtp[32], l_buf[64];
    char *p_str;
    sprintf (l_fmtp, "%%.%df", n);
    if (dval>=0)
            sprintf (l_buf, l_fmtp, dval);
    else
            sprintf (l_buf, l_fmtp, dval);
    return ((double)strtod(l_buf, &p_str));

}

这里n是小数的个数

例子:

double d = 100.23456;

printf("%f", f_round(d, 4));// result: 100.2346

printf("%f", f_round(d, 2));// result: 100.23

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

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;

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