Python float to int conversion

前端 未结 5 1032
南笙
南笙 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:50

    2.51 * 100 = 250.999999999997
    

    The int() function simply truncates the number at the decimal point, giving 250. Use

    int(round(2.51*100)) 
    

    to get 251 as an integer. In general, floating point numbers cannot be represented exactly. One should therefore be careful of round-off errors. As mentioned, this is not a Python-specific problem. It's a recurring problem in all computer languages.

提交回复
热议问题