Limit floating point precision?

46,034

Solution 1

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)); 
}

Solution 2

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

Solution 3

Multiply by 100, round to integer (anyway you want), divide by 100. Note that since 1/100 cannot be represented precisely in floating point, consider keeping fixed-precision integers.

Solution 4

For those of you googling to format a float to money like I was:

#include <iomanip>
#include <sstream>
#include <string>

std::string money_format (float val)
{
    std::ostringstream oss;

    oss << std::fixed << std::setfill ('0') << std::setprecision (2) << val;

    return oss.str();
}
// 12.3456 --> "12.35"
// 1.2 --> "1.20"

You must return it as a string. Putting it back into a float will lose the precision.

Solution 5

Don't use floats. Use integers storing the number of cents and print a decimal point before the last 2 places if you want to print dollars. Floats are almost always wrong for money unless you're doing simplistic calculations (like naive economic mathematical models) where only the magnitude of the numbers really matters and you never subtract nearby numbers.

Share:
46,034
jmasterx
Author by

jmasterx

Hi

Updated on January 06, 2021

Comments

  • jmasterx
    jmasterx over 3 years

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