-1

I have a quick question in terms of decimals points in Python 2. Here is the code in Python 2:

a = 1500/1589
print (round(a,2))
#0.0

I thought it would print out a = 0.94 as it did in Python 3. I am just wondering how I could get 2 decimals for my answer.

Suever
  • 64,497
  • 14
  • 82
  • 101
yingnan liu
  • 409
  • 1
  • 8
  • 18

2 Answers2

1

You need to specify that at least one of the inputs to the division is a floating point number by adding an explicit decimal point.

a = 1500. / 1589
print round(a, 2)
# 0.94

If you do not do this, both 1500 and 1589 are treated as integers and the result of 1500/1589 is required to be an integer (0) as well

1500 / 1589
# 0

print round(1500 / 1589, 2)
# 0.0

As a side note, if you want to print a number with two decimal places, a far easier method is to create a formatted string:

print '%0.2f' % (1500. / 1589)
# 0.94

print '{:.2}'.format(1500. / 1589)
# 0.94
Suever
  • 64,497
  • 14
  • 82
  • 101
0

That's because you're making an integer division. For instance do:

a = 1500.0/1589.0
print round(a,2)

Or if you have integers as input:

a = float(1500)/float(1589)
print round(a,2)
zaphodef
  • 363
  • 2
  • 10