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++?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With