Skip to content
Advertisement

float(’25’) works but int(‘25.2’) doesn’t. Why?

>>> float('25')
25.0
>>> int('25.2')
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    int('25.2')
ValueError: invalid literal for int() with base 10: '25.2'

Why do I get an error on int(‘25.2′) and don’t get one on float(’25’)?

Advertisement

Answer

Python is trying to prevent you from accidentally losing the information after the decimal point by converting a string to an integer when you should have converted it to a float.

However, it does allow converting a float to an integer, so with a little more explicit code you can convert a string with a decimal point to an integer:

>>> float('1.6')
1.6
>>> int('1.6')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1.6'
>>> int(1.6)
1
>>> int(float('1.6'))
1
>>> round(1.6)
2
>>> round(float('1.6'))
2
>>> round(float('1.2'))
1

Note that int always rounds down, simply dropping the fractional part, while round rounds to the nearest integer.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement