3

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?

8
  • 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). Commented Nov 23, 2019 at 18:57
  • To round; en.cppreference.com/w/c/numeric/math/round Commented Nov 23, 2019 at 19:02
  • Note that floating point are usually NOT decimal values. See stackoverflow.com/questions/588004/… for more information. Commented Nov 25, 2019 at 13:45
  • @AProgrammer: the OP means fractional values. Commented Nov 25, 2019 at 15:50
  • @templatetypedef: what ??? What does "older C++ versions" have to do with this ? Commented Nov 25, 2019 at 15:53

1 Answer 1

5

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!

Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.