Round double to 3 points decimal [duplicate]

Solution 1:

A common trick is to do it with maths:

value = round( value * 1000.0 ) / 1000.0;

Where round will handle negative and positive values correctly... Something like this (untested):

inline double round( double val )
{
    if( val < 0 ) return ceil(val - 0.5);
    return floor(val + 0.5);
}

You'll still want to set the decimal places to 3 during output, due to floating point precision problems.

Solution 2:

I know this is a very old post but I was looking for a solution to the same problem. However, I did not want to create a special function for it so I came up with the following:

#include <sstream>
#include <iomanip>
...
...
...
double val = 3.14159;
stringstream tmp;
tmp << setprecision(3) << fixed << val;
double new_val = stod(tmp.str());   // new_val = 3.143
tmp.str(string());                  // clear tmp for future use

Not sure if this is the best way to do it but it worked for me!