Why int() cannot pass a string representation of a float into int? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Why int() cannot pass a string representation of a float into int? (/thread-28192.html) |
Why int() cannot pass a string representation of a float into int? - majorjohnusa - Jul-09-2020 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! RE: Why int() cannot pass a string representation of a float into int? - Knight18 - Jul-09-2020 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. |