Python float to int conversion

前端 未结 5 1020
南笙
南笙 2020-11-28 09:13

Basically, I\'m converting a float to an int, but I don\'t always have the expected value.

Here\'s the code I\'m executing:

x = 2.51

print(\"         


        
5条回答
  •  情歌与酒
    2020-11-28 09:29

    What Every Computer Scientist Should Know About Floating-Point Arithmetic

    Floating-point numbers cannot represent all the numbers. In particular, 2.51 cannot be represented by a floating-point number, and is represented by a number very close to it:

    >>> print "%.16f" % 2.51
    2.5099999999999998
    >>> 2.51*100
    250.99999999999997
    >>> 4.02*100
    401.99999999999994
    

    If you use int, which truncates the numbers, you get:

    250
    401
    

    Have a look at the Decimal type.

提交回复
热议问题