Limit floating point precision?

2019-01-19 00:53发布

Is there a way to round floating points to 2 points? E.g.: 3576.7675745342556 becomes 3576.76.

9条回答
2楼-- · 2019-01-19 01:21

To limit the precision:
If x is a float, no rounding:
(shift up by 2 decimal digits, strip the fraction, shift down by 2 decimal digits)

((int)(x*100.0)) / 100.0F

Float w/ rounding:

((int)(x*100.0 + 0.5F)) / 100.0F

Double w/o rounding:

((long int)(x*100.0)) / 100.0

Double w/ rounding:

((long int)(x*100.0 + 0.5)) / 100.0

Note: Because x is either a float or a double, the fractional part will always be there. It is the difference between how a # is represented (IEEE 754) and the #'s precision.
C99 supports round()

查看更多
We Are One
3楼-- · 2019-01-19 01:24
round(x * 100) / 100.0

If you must keep things floats:

roundf(x * 100) / 100.0

Flexible version using standard library functions:

double GetFloatPrecision(double value, double precision)
{
    return (floor((value * pow(10, precision) + 0.5)) / pow(10, precision)); 
}
查看更多
三岁会撩人
4楼-- · 2019-01-19 01:31

If you are printing it out, instead use whatever print formatting function available to you.

In c++

cout << setprecision(2) << f; 

For rounding to render to GUI, use std::ostringstream

查看更多
登录 后发表回答