can anyone explain why a ValueError occurs when I try to convert a float datatype enclosed within quotation marks to an integer datatype?
Example of when ValueError occurs:
print(int("7.3"))
However, when I try to convert a value such as:
print(int(7.3))
No error occurs when trying to convert 7.3 not enclosed within quotation marks to an integer datatype
CodePudding user response:
Because the string "7.3"
can't be parsed as an integer (due to the decimal dot). int
tries to "cast" the value it gets to integer. For floats, this means flooring them; for strings, this means parsing them as ints. The string you are providing can't be parsed as an int because it is a textual float representation. For float parsing, use float
:
ìnt(float("7.3"))
will first parse "7.3"
as the float 7.3
which will then be floored to 7
by int
.
CodePudding user response:
From python docs
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating point numbers, this truncates towards zero.
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 the given base.
But what you are providing is a string which is representing a float literal instead of an integer literal.
To parse a string representing float to integer, this should work:
int(float("7.3"))