1

Suppose I have a string:

temp = "0.1"

When I run int(temp):

I get the following error:

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

But when I run int(float(temp)):

I get the correct output i.e. 0


Why does converting to float and then converting to int work but directly converting to int not work ?

Thanks and regards

Agile_Eagle
  • 1,710
  • 3
  • 13
  • 32

5 Answers5

6

It is because your string has float format. So when you directly cast "0.1" to int, it returns a error. But if you cast to float and after to int, it is able to truncate your number.

Eduardo Soares
  • 992
  • 4
  • 14
4

This is documented behaviour (emphasis mine):

If x is a number, it can be a plain integer, a long integer, or a floating point number. If x is floating point, the conversion truncates towards zero.

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 radix base

So as to your question why, the only answer is: because it is like that by design.

Community
  • 1
  • 1
trincot
  • 317,000
  • 35
  • 244
  • 286
2

From the python docs

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. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35. The default base is 10. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code.

then x must be a string, bytes, or bytearray instance representing an integer So if you add a . to the string it won't represent an integer anymore

Ishan Srivastava
  • 1,129
  • 1
  • 11
  • 29
1

If you pass a string to int, it only works if the string directly represents an integer. It doesn't work if the string represents a non-integer number. But if you pass a float to int, it always works, by truncating the float. int just doesn't accept "strings that could be made into ints by first making them into floats and then truncating them"; it only accepts strings that directly represent integers. That's just how int works.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
1

The difference is that numeric objects like floats have a special __int__ or __trunc__ method which computes their integer value while strings are parsed. See int() in the docs.

Thus the result of int(0.1) comes from the O.1 object and the result of int("0.1") comes from the int() function.

VPfB
  • 14,927
  • 6
  • 41
  • 75