-1

Please tell me how to round up numbers in Python.

If I have 1.47, how to round it up to 2 ? Or if I have 10.13, how to round it up to 11?

The answer is correct with round(round(1.47, 1)), but is there another way to round up such numbers?

aronaks
  • 53
  • 7

3 Answers3

3

There is a function for that in the math module called ceil.

>>> import math
>>> print math.ceil(1.47)
2.0

If you want an integer,

>>> import math
>>> print int(math.ceil(1.47))
2
zondo
  • 19,901
  • 8
  • 44
  • 83
2

Obviously use math.ceil, but here's a fun alternative anyway:

>>> [-(-x//1) for x in 1.47, 10.13, 2.0]
[2.0, 11.0, 2.0]

And an even shorter/funnier one:

>>> [0--x//1 for x in 1.47, 10.13, 2.0]
[2.0, 11.0, 2.0]

Or --0-- x//1, see @MarkDickinson's comment below.

Apply int(...) if you want an int, I'll just keep these as they are to showcase "integer division for floats" and to keep it visible what's happening.

Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
  • wrap results in int, seems like it's what OP wants – midori Feb 05 '16 at 02:49
  • Thanks, I mentioned it now. – Stefan Pochmann Feb 05 '16 at 03:07
  • I like to write the second example as `[--0-- x//1 for x in 1.47, 10.13, 2.0]`: `--0--` is the "ceiling division operator", which converts a subsequent floor division to do ceiling division instead. (Yes, technically `0--` works just as well, but `--0--` looks so much better.) – Mark Dickinson Feb 05 '16 at 07:34
  • @MarkDickinson Ha, I googled "ceiling division operator" to see how popular it is, got three results, and the first is [your comment](http://stackoverflow.com/questions/33299093/how-to-perform-ceiling-division-in-integer-arithmetic/33299457#comment54417923_33299093) referring to my own earlier answer. So **that's** why this felt so familiar :-). I like your way and how you're thinking of it. I also still like mine, though, for the symmetry (x being in the middle of two "double operators" and the numbers). – Stefan Pochmann Feb 05 '16 at 13:40
0

You'll want to use the math ceiling function, namely ceil:

import math
print math.ceil(1.47)

will yield 2.0

wogsland
  • 9,106
  • 19
  • 57
  • 93