1

I know that you can use setprecision(x) to limit the amount of decimals displayed in the cout method. I was wondering how do I round a single decimal place up/down?

For example: I have the number: 0.073

I want to round 7 upwards even though the number after 7 is 3. So the number becomes: 0.08

I have tried using ceil and floor, but that only rounds it to a whole number. I have ceilf as well, and that rounds to a whole number too.

Tommy Saechao
  • 1,099
  • 4
  • 17
  • 28
  • `std::cout` is not a method. It's an object. You use `setprecision(x)` to control the number of decimals displayed by the **stream inserter**, `operator<<`. – Pete Becker Jan 30 '16 at 22:08

2 Answers2

3

Two possibilities if you always have numbers of that order of magnitude,

  • either add 0.005 before rounding
  • or multiply by 100, use ceil and then divide by 100.

If you have numbers of different orders of magnitute, use log10 to find the order of magnitude and then do your rounding by one of the methods above.

MortenSickel
  • 2,118
  • 4
  • 26
  • 44
  • Note that both options assume you know, in advance, the number of decimal places (two in this case) you are seeking in the result. – Peter Jan 30 '16 at 22:21
  • Yup, you need to have one way of knowing where to round, either because you always want a fixed number of decimals, or because you can use some calculations to find the decimal place you want to round at - usually using -ceil(log10(number)) and possibly adding or subtracting something. – MortenSickel Jan 30 '16 at 22:26
-1

Since you wanted the answer for cpp, you should be using ceil function from the cmath library. More information can be found at: http://en.cppreference.com/w/cpp/numeric/math/ceil

ucsunil
  • 7,378
  • 1
  • 27
  • 32