Round double to 3 points decimal [duplicate]

Currently, I can round a double to an output stream using:

output.setf(std::ios::fixed,std::ios::floatfield); output.precision(3); 

But I'm given a double and I need to make the conversion before I insert it to a vector. So for instance, if the number -0.00078 appears then it equals to 0.000 and I won't need to save it. On the other hand, 1.0009 will become 1.001 (same as the precision function handles it).

How can I convert doubles like that in C++?

5

4 Answers

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.

6

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!

1

Other answers here have given you a technique. But it's important to mention that not all values can be exactly represented in floating-point. 1.001 is a good example; the nearest possible value is 1.00099999999999988987.

So if your aim is to get strictly 3 decimal places, then the answer is: that's not possible.

2

You can multiply it by 1000 and then round (or truncate) it; this will give you a value 1000 times the 3-decimal place value. Note that, if you divide it by 1000 to get the 'rounded' value, you may end up w/ more than 3 decimal places (due to round off error).

1

You Might Also Like