Is there a function or an algorithm to round up float numbers to 2 digits after the radix point (comma).
Example: 3.1457 ->Rounds up to-> 3.14
This is a discussion on Rounding up float numbers within the C++ Programming forums, part of the General Programming Boards category; Is there a function or an algorithm to round up float numbers to 2 digits after the radix point (comma). ...
Is there a function or an algorithm to round up float numbers to 2 digits after the radix point (comma).
Example: 3.1457 ->Rounds up to-> 3.14
"A Computer in every desk and in every home, running Microsoft software."
If it's for display purposes, look up std::setprecision. Otherwise, add .005 or however it would work mathematically.
If you need the mathematical result (rather than display purposes) use std::ceil(value*100.0)/100.0
There are some limits on the range of values this works for (and this assumes a positive value) but, if you are asking the question, you are unlikely to be working outside the relevant range.
Last edited by grumpy; 06-12-2011 at 06:25 AM.
Right 98% of the time, and don't care about the other 3%.
Works without these limits.Code:double round_floating_2(double x) { return x - std::fmod(x, 0.01); }
I never put signature, but I decided to make an exception.
Yes, it's rounding down.
"A Computer in every desk and in every home, running Microsoft software."