2

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?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • 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 Nov 23 '19 at 18:57
  • To round; https://en.cppreference.com/w/c/numeric/math/round – Jesper Juhl Nov 23 '19 at 19:02
  • Note that floating point are usually **NOT** decimal values. See https://stackoverflow.com/questions/588004/is-floating-point-math-broken for more information. – AProgrammer Nov 25 '19 at 13:45
  • @AProgrammer: the OP means fractional values. –  Nov 25 '19 at 15:50
  • @templatetypedef: what ??? What does "older C++ versions" have to do with this ? –  Nov 25 '19 at 15:53
  • @YvesDaoust, are you sure? I've seen far too many people wondering why adding 0.9 to 0.1 is not equal to 1.0 not to try to avoid that second question. – AProgrammer Nov 25 '19 at 16:17
  • @AProgrammer: more than sure. Read the question. –  Nov 25 '19 at 16:27
  • @YvesDaoust There was an earlier, but since deleted, comment suggesting a question this might have been a duplicate of. That question was about an equivalent to std::round for C++98. – templatetypedef Nov 26 '19 at 00:03

1 Answers1

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!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • 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? – walnut Nov 23 '19 at 19:07
  • 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. – templatetypedef Nov 23 '19 at 20:42
  • 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. – chux - Reinstate Monica Nov 25 '19 at 15:50