JavaScript
x
8
1
>>> float('25')
2
25.0
3
>>> int('25.2')
4
Traceback (most recent call last):
5
File "<pyshell#26>", line 1, in <module>
6
int('25.2')
7
ValueError: invalid literal for int() with base 10: '25.2'
8
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:
JavaScript
1
17
17
1
>>> float('1.6')
2
1.6
3
>>> int('1.6')
4
Traceback (most recent call last):
5
File "<stdin>", line 1, in <module>
6
ValueError: invalid literal for int() with base 10: '1.6'
7
>>> int(1.6)
8
1
9
>>> int(float('1.6'))
10
1
11
>>> round(1.6)
12
2
13
>>> round(float('1.6'))
14
2
15
>>> round(float('1.2'))
16
1
17
Note that int
always rounds down, simply dropping the fractional part, while round
rounds to the nearest integer.