Python Forum

Full Version: Why int() cannot pass a string representation of a float into int?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Dear all,
I have a rookie question.

In the following codes, we know that the second one will result in a ValueError, because the "int()" command cannot pass a string representation of a float into int. But why "float()" can do the opposite? Why "float()" can pass a string representation of an integer into float, when int() cannot pass a string of float into integer?
print (int("4"))
print (int("4.1"))
print (float("4"))
print (float("4.1"))
I know how to solve it by converting the string representation of a float into float first: print (int(float("4.1"))), but I am just curious why.

Many thanks in advance!
Because float will convert "4" to 4.0, which is a float. On the other hand, you simply can't have an integer with a value of 4.1, hence it fails.

You could try stuff like rounding off or truncating before passing a float value to the int() function.