Python 2.7 and 3.3.2, why int ('0.0') doesn't work?

As the name says, in Python (I tried in 2.7 and 3.3.2), why int('0.0') doesn't work? He gives this error:

 ValueError: invalid literal for int() with base 10: '0.0' 

If you try int('0') or int(eval('0.0')) , it will work ...

+7
source share
4 answers

Just because 0.0 not a valid integer of base 10. Although 0 is.

Read about int() here.

int (x, base = 10)

Convert the number or string x to an integer or return 0 if no arguments are given. If x is a number, it can be a simple integer, a long integer, or a floating point number. If x floats a point, the transformation truncates to zero. If the argument is outside the integer range, the function returns a long object instead.

If x is not a number or a base value is specified, then x must be a string or a Unicode object representing an integer literal in the base database. Optionally, a literal can be preceded by + or - (without a space in between) and surrounded by spaces. The literature base-n consists of numbers from 0 to n-1, from a to z (or from A to Z), with values ​​from 10 to 35. The default base is 10. Allowed values ​​are 0 and 2-36. Base-2, -8, and -16 literals can optionally be the prefix 0b / 0B, 0o / 0O / 0 or 0x / 0X, as with integer literals in the code. A base of 0 means interpreting the string exactly as an integer literal, so the actual base is 2, 8, 10, or 16.

+4
source

In the docs on int :

 int(x=0) -> int or long int(x, base=10) -> int or long 

If x is not a number or if a base is given, then x must be a string or a Unicode object representing an integer literal in the given base.

So, '0.0' is an invalid integer literal for base 10.

You need:

 >>> int(float('0.0')) 0 

help int :

 >>> print int.__doc__ int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) 4 
+12
source

If you need, you can use

 int(float('0.0')) 
+3
source

What you are trying to do is convert a string literal to int. '0.0' cannot be parsed for an integer because it contains a decimal point and therefore cannot be considered as an integer.

However, if you use

 int(0.0) 

or

 int(float('0.0')) 

he will understand correctly.

+3
source

All Articles