c++calgorithmfloating-pointfloating-point-conversion

Limit floating point precision?


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


Solution

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