Round double to 3 points decimal [duplicate]

A common trick is to do it with math:

value = std::round(value * 1000.0) / 1000.0;

This scales the value, applies ordinary rounding and then scales it back. You may have some precision loss as is typical with floating-point math, and this won’t be effective at extreme ranges of what can be represented by double, but often it’s “good enough”.

For something more generalized, put this in a function that accepts rounding to any amount:

double round_to(double value, double precision = 1.0)
{
    return std::round(value / precision) * precision;
}

Example:

#include <cmath>
#include <iostream>

double round_to(double value, double precision = 1.0)
{
    return std::round(value / precision) * precision;
}

int main()
{
    double value = 10.0078;
    double precision[] = { 0.001, 0.01, 0.1, 1, 2, 3, 4 };
    for (double p : precision)
    {
        double result = round_to(value, p);
        std::cout << "round_to(" << value << ", " << p << ") = " << result << "\n";
    }
}

Output:

round_to(10.0078, 0.001) = 10.008
round_to(10.0078, 0.01) = 10.01
round_to(10.0078, 0.1) = 10
round_to(10.0078, 1) = 10
round_to(10.0078, 2) = 10
round_to(10.0078, 3) = 9
round_to(10.0078, 4) = 12

Leave a Comment