If I have, for example, the number 9.83333 and I want to round it to 9.84 or 9.9. How can I do this?
- 1@ruohola That question seems to address older C++ versions and rounding to the nearest integer, rather than what this question seems to be abound (rounding to nearest tenths or hundredths).templatetypedef– templatetypedef2019-11-23 18:57:43 +00:00Commented Nov 23, 2019 at 18:57
- To round; en.cppreference.com/w/c/numeric/math/roundJesper Juhl– Jesper Juhl2019-11-23 19:02:25 +00:00Commented Nov 23, 2019 at 19:02
- Note that floating point are usually NOT decimal values. See stackoverflow.com/questions/588004/… for more information.AProgrammer– AProgrammer2019-11-25 13:45:26 +00:00Commented Nov 25, 2019 at 13:45
- @AProgrammer: the OP means fractional values.user1196549– user11965492019-11-25 15:50:35 +00:00Commented Nov 25, 2019 at 15:50
- @templatetypedef: what ??? What does "older C++ versions" have to do with this ?user1196549– user11965492019-11-25 15:53:40 +00:00Commented Nov 25, 2019 at 15:53
| Show 3 more comments
1 Answer
There’s a function called std::round in the <cmath> header file that rounds a real number to the nearest integer. You can use that to round to the nearest tenth by computing std::round(10 * x) / 10.0, or to the nearest hundredth by calling std::round(100 * x) / 100.0. (Do you see why that works?)
You seem to be more interested in rounding up rather than rounding to the nearest value, which you can do by using the std::ceil function rather than std::round. However, the same basic techniques above still work for this.
Hope this helps!
3 Comments
walnut
Why did you choose to use floating point literals for the division which is done in a floating point type anyway after arithmetic conversions, but an integer literal for the multiplication?
templatetypedef
No reason. :-) I figure that marking the division as a floating point operation might make it clearer to readers that indeed the result is floating-point.
chux
For the pedantic, the first scaling like
10 * x can incur a rounding such that round() provides the wrong answer. This happens in select half way cases near x.x5. Also 10 * x may overflow - easy enough to pre-test as all large double are whole numbers and need no fractional decimal rounding.