Reputation: 43
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?
Upvotes: 3
Views: 5867
Reputation: 373112
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!
Upvotes: 5