Limit floating point precision?

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

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.


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.


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