Skip to content
Advertisement

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

JavaScript

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

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