Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round double to 3 points decimal [duplicate]

Tags:

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++?

like image 468
Tom Avatar asked Jan 16 '13 23:01

Tom


1 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.

like image 177
paddy Avatar answered Sep 20 '22 20:09

paddy