Tommy Saechao
Tommy Saechao

Reputation: 1139

How do I round up/down a decimal place of a float value? C++

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.

Upvotes: 1

Views: 1352

Answers (2)

MortenSickel
MortenSickel

Reputation: 2200

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.

Upvotes: 3

ucsunil
ucsunil

Reputation: 7494

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

Upvotes: -1

Related Questions