Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I round up decimal values in C++?

Tags:

c++

math

rounding

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?

like image 712
forestgump221 Avatar asked Jan 21 '26 03:01

forestgump221


1 Answers

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!

like image 154
templatetypedef Avatar answered Jan 22 '26 16:01

templatetypedef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!