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?
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?
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
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.
You'll want to use the math
ceiling function, namely ceil
:
import math
print math.ceil(1.47)
will yield 2.0