CasualProgrammer
CasualProgrammer

Reputation: 3

I can't get a float in python division

I was coding and I had this problem where I devide 5 / 2 and still get 2, not 2.5, and i get integers only. I don't know if it's a glitch, different python files give you either 2 or 2.5. I need help!

print(5 / 2)
>>>2

what's supposed to happen:

print(5 / 2)
>>>2.5

It even happens when I do:

print(float(5 / 2))
>>>2  

see? Still can't be a float as it's supposed to be!

Upvotes: 0

Views: 1230

Answers (1)

Óscar López
Óscar López

Reputation: 235984

You're probably using an old Python version (previous to Python 3.x), that performs integer division by default. Try this:

5.0 / 2.0
=> 2.5

Or this:

from __future__ import division
5 / 2
=> 2.5

But as the comments mention, it'd be better if you upgraded to Python 3.x, the 2.x version was deprecated.

Upvotes: 3

Related Questions