標籤:
在Python中,round函數對小數進行四捨五入的截斷。
然而:
>>> round(3.55, 1)3.5
官方文檔對於函數的解釋是:
Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine.
>>> round(0.55, 1)0.6>>> round(3.55, 1)3.5
>>> from decimal import Decimal>>> Decimal(0.55)Decimal(‘0.5500000000000000444089209850062616169452667236328125‘)>>> Decimal(3.55)Decimal(‘3.54999999999999982236431605997495353221893310546875‘)
一種正確四捨五入的解決方案是用decimal模組實現:
from decimal import *number = ‘17.9555‘print Context(prec = len(number.split(‘.‘)[0]) + 3, rounding = ROUND_HALF_UP).create_decimal(number)
代碼裡加粗部分的解釋:
- number用字串表示,避免轉換為Decimal時,浮點數儲存產生的精度問題。
- prec:前面的len函數求的是整數部分的長度,後面的3是保留的小數位元。
- rounding:ROUND_HALF_UP表示四捨五入。
[Python] round函數