Md. Mohsin
Md. Mohsin

Reputation: 1832

Rounding Up a Number in Python

I am trying to round up a number using math module in python.

So when I do,

print math.ceil(21/10)

I get '2.0' which is right.

print math.ceil(27/10)

I still get '2.0'

I want to get 3, since it is closest to 2.7

Could someone please advise a workaround.

Thanks in advance.

Upvotes: 1

Views: 228

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

I think you want round:

from __future__ import division

print round(27/10)
3.0
print round(21/10)
2.0

math.ceil will always round up, round will round to the nearest

You only get 2 from math.ceil(21/10) because of how python2 handles integer division.

21/10 in python2 is 2

Upvotes: 1

Tim 333
Tim 333

Reputation: 952

The problem is Python thinks 27/10 are integers and so the evaluates that as 2. If you write 27/10.0 it will make them floats and the thing will work as you want.

Upvotes: 0

steveha
steveha

Reputation: 76695

You are being surprised by the division operator in Python 2.x. With integers, it does integer division; 21/10 results in 2 and 27/10 results in 2.

Use 21.0/10 and 27.0/10 and you will get the correct answers.

In Python 3.x, division of integers will automatically promote to float if the division isn't even (there would be a remainder). You can get this behavior in Python 2.7 by using from __future__ import division.

By the way, pretty sure the integer ceiling of 21/10 should be 3.

Upvotes: 2

Related Questions