It's clearly stated in the docs that int(number) is a flooring type conversion:
int(1.23) 1
and int(string) returns an int if and only if the string is an integer literal.
int('1.23') ValueError int('1') 1
Is there any special reason for that? I find it counterintuitive that the function floors in one case, but not the other.
Python int() Function The int() function converts the specified value into an integer number.
int() Return Value The int() method returns: integer portion of the number - for a single argument value (any number) 0 - for no arguments. integer representation of a number with a given base (0, 2 ,8 ,10,16)
To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .
There is no special reason. Python is simply applying its general principle of not performing implicit conversions, which are well-known causes of problems, particularly for newcomers, in languages such as Perl and Javascript.
int(some_string)
is an explicit request to convert a string to integer format; the rules for this conversion specify that the string must contain a valid integer literal representation. int(float)
is an explicit request to convert a float to an integer; the rules for this conversion specify that the float's fractional portion will be truncated.
In order for int("3.1459")
to return 3
the interpreter would have to implicitly convert the string to a float. Since Python doesn't support implicit conversions, it chooses to raise an exception instead.
This is almost certainly a case of applying three of the principles from the Zen of Python:
Explicit is better implicit.
[...] practicality beats purity
Errors should never pass silently
Some percentage of the time, someone doing int('1.23')
is calling the wrong conversion for their use case, and wants something like float
or decimal.Decimal
instead. In these cases, it's clearly better for them to get an immediate error that they can fix, rather than silently giving the wrong value.
In the case that you do want to truncate that to an int, it is trivial to explicitly do so by passing it through float
first, and then calling one of int
, round
, trunc
, floor
or ceil
as appropriate. This also makes your code more self-documenting, guarding against a later modification "correcting" a hypothetical silently-truncating int
call to float
by making it clear that the rounded value is what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With