[英]How to properly truncate a float/decimal to a specific place after the decimal in python?
在Python 2.7.3中,這是當前的行為:
>>> 8./9.
0.8888888888888888
>>> '%.1f' % (8./9.)
'0.9'
對於Decimal
似乎也是如此:
>>> from decimal import Decimal
>>> Decimal(8) / Decimal(9)
Decimal('0.8888888888888888888888888889')
>>> '%.1f' % (Decimal(8) / Decimal(9))
'0.9'
我本來期望截斷,但它似乎是圓的。 所以我選擇截斷到十分位置?
我問,因為我目前的解決方案看起來很糟糕(但也許是最好的做法?)因為它會產生一個結果字符串,找到句點並在我想要的句號之后簡單地找到X位數。
您正在尋找math.floor()
函數 :
>>> import math
>>> math.floor(8./9. * 10) / 10
0.8
所以我選擇截斷到十分位置?
Decimal.quantize()方法將數字四舍五入為固定指數,並提供對舍入模式的控制:
>>> from decimal import Decimal, ROUND_FLOOR
>>> Decimal('0.9876').quantize(Decimal('0.1'), rounding=ROUND_FLOOR)
Decimal('0.9')
不要在Decimal值上使用math.floor ,因為它首先將它們強制轉換為引入表示錯誤和丟失精度的二進制浮點數:
>>> x = Decimal('1.999999999999999999998')
>>> x.quantize(Decimal('0.1'), rounding=ROUND_FLOOR)
Decimal('1.9')
>>> math.floor(x * 10) / 10
2.0
乘以10,然后將值降低。
用某種語言:
float f = 1/3;
print(f) //Prints 0,3333333333
float q = Math.floor(f*10)/10
print(q) //Prints 0,3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.