我試圖用我在下面找到的代碼四舍五入一個小數,但它在 python(django) 中似乎不能正常作業。這是代碼:
import math
def round_up(n, decimals=0):
multiplier = 10 ** decimals
return math.ceil(n * multiplier) / multiplier
以下是我運行該函式時得到的一些結果:
print(round_up(20.232, 2))
print(round_up(20.211, 2))
print(round_up(20.4, 2))
20.24
20.22
20.4
但是,由于某種原因,當我輸入 80.4 時,我得到了一個奇怪的值。我得到的是 80.41 而不是 80.4:
print(round_up(80.4, 2))
80.41
有沒有其他方法可以在python(django)中四舍五入小數?我已經從互聯網上得到了這個,所以除了我上面提到的問題(輸入 80.4)之外,可能還有其他一些問題。基本上,我只想像上面一樣將小數四舍五入到第二個小數點(當然,四舍五入 80.4 或 20.3 分別是 80.4 和 20.3)。謝謝,請留下您的任何問題。
uj5u.com熱心網友回復:
乘以浮點數時出現問題
>>> 80.4 * 100
8040.000000000001
所以, math.ceil(80.4 * 100) == 8041
如果你想精確,你可以使用十進制
from decimal import Decimal, ROUND_CEILING
def round_up_decimal(n, decimals=0):
multiplier = Decimal(10 ** decimals)
return (n * multiplier).to_integral(rounding=ROUND_CEILING) / multiplier
print(round_up_decimal(Decimal("20.232"), 2))
print(round_up_decimal(Decimal("20.0"), 2))
print(round_up_decimal(Decimal("20.4"), 2))
print(round_up_decimal(Decimal("80.4"), 2))
輸出
20.24
20
20.4
80.4
此外,您可以創建另一個函式來處理 float
def round_up_float(n, decimals=0):
return float(round_up_decimal(Decimal(str(n)), decimals)) # uses previous function
print(round_up_float(Decimal("20.232"), 2))
print(round_up_float(Decimal("20.0"), 2))
print(round_up_float(Decimal("20.4"), 2))
print(round_up_float(Decimal("80.4"), 2))
輸出
20.24
20.0
20.4
80.4
uj5u.com熱心網友回復:
我可能誤解了你的問題,但據我所知,我想寫下來以防萬一。
您是否嘗試過Python 中已有的round()函式?
round(20.232, 2)
round(20.0, 2)
round(20.4, 2)
round(80.4, 2)
20.23
20.0
20.4
80.4
我再說一遍,我就我理解的回答了,當然,這是一個現成的功能,可能不是你想要的,但如果有幫助,我會很高興。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/395948.html
