Limit floating point precision?

jmasterx picture jmasterx · Aug 1, 2010 · Viewed 44.3k times · Source

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

Answer

strager picture strager · Aug 1, 2010
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)); 
}