0

So i ran into trouble rounding floats up, this is my code:

foo = float(0.21)
bar = float(0.871929)

foobar = foo * bar
Rfoobar = round(foobar,2)

This gives me:

foobar = 0.1831
Rfoobar = 0.18

But i want Rfoobar to be 0.19, how do i accomplish that it always rounds up the digits when there is a remainder?

I read about math.ceiling but in my case that doesn't seem to do the trick.

any help is greatly appreciated.

Lyux
  • 453
  • 1
  • 10
  • 22

2 Answers2

2

Just move the decimal point before and after calling ceil:

from math import ceil

Rfoobar = ceil(foobar * 100) / 100

If the number of decimals varies, you can do something like:

Rfoobar = ceil(foobar * 10 ** digits) / 10 ** digits
Tom Zych
  • 13,329
  • 9
  • 36
  • 53
2

You could also add 0.005 before rounding:

>>> for foobar in 0.1831, 0.1801, 0.1800:
        print(foobar, '->', round(foobar + 0.005, 2))

0.1831 -> 0.19
0.1801 -> 0.19
0.18 -> 0.18
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107