0

Apologies if this has already been asked but why does this:

a=4
b=5
c=float(a/b)

print c

Gives

>>>>
0.0

rather than 0.8?

Matthias
  • 12,873
  • 6
  • 42
  • 48
Lio Elbammalf
  • 196
  • 1
  • 12

6 Answers6

4

That's because this is an integer division:

>>> 4/5
0

if you want to get 0.8, cast one of the two to float before the division:

>>> 4/float(5)
0.8
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
2

In Python 2, division between 2 integers will return an integer (rounding to the closest integer to 0), in this case, 0. Your code is basically float(0) which is 0.0.

You would need to change one of your values to a float first if you want to return a float.

This behavior is changed in Python 3, where division between 2 integers will return a float, 0.8 in this case.

pferate
  • 2,067
  • 1
  • 16
  • 18
2

If you do not want to introduce float in one of the variables. You could do this:

from __future__ import division

4/5

This will give what you are looking for 0.8, without having to introduce floating.

Prayson W. Daniel
  • 14,191
  • 4
  • 51
  • 57
1

In Python 2 / returns only integer part if you use two integers - like int(0.8). You have to use float ie. float(a) or 4.0 (shortly 4.) or * 1.0

print float(4)/5
print 4/float(5)

print 4.0/5
print 4/5.0

print 4./5
print 4/5.

print a*1.0/b   # sometimes you can see this method 
print a/(b*1.0) # this version need () - without () you get (a/b)*1.0
furas
  • 134,197
  • 12
  • 106
  • 148
0

4/5 will return 0 because it's an int division, then you cast float on 0

JMat
  • 752
  • 6
  • 14
0

Because of integer division....dividing two integers will return and integer. The value of 0.8 is truncated to 0.

You need to elevate one of your integers to a float if you want a floating point answer.

E.G.

c = float(a) / b

ccbunney
  • 2,282
  • 4
  • 26
  • 42