Counterintuitive behaviour of int() in python

后端 未结 4 1414
故里飘歌
故里飘歌 2021-02-04 23:07

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

4条回答
  •  攒了一身酷
    2021-02-04 23:47

    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.

提交回复
热议问题