Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int() not working for floats?

I recently ran into this in Python 3.5:

>>> flt = '3.14'
>>> integer = '5'
>>> float(integer)
5.0
>>> float(flt)
3.14
>>> int(integer)
5
>>> int(flt)
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    int(flt)
ValueError: invalid literal for int() with base 10: '3.14'

Why is this? It seems like it should return 3. Am I doing something wrong, or does this happen for a good reason?

like image 677
nedla2004 Avatar asked Nov 28 '25 00:11

nedla2004


1 Answers

int() expects an number or string that contains an integer literal. Per the Python 3.5.2 documentation:

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base. (Emphasis added)

Meaning int() can only convert strings that contain integers. You can easily do this:

>>> flt = '3.14'
>>> int(float(flt))
3

This will convert flt into a float, which is then valid for int() because it is a number. Then it will convert to integer by removing fractional parts.

like image 134
Andrew Li Avatar answered Nov 29 '25 16:11

Andrew Li