[英]How to represent values float in 2 float point in python?
我需要計算 float 類型的值,因此,在 python 中,0.01 不是 0.01 而是 0.10000000000000001 + 一些數字(由 python 文檔 Floating 引用)。
好的,我的function需要計算每個值的硬幣數量。
def calcula_moedas(resto):
moedas = [0.5, 0.1, 0.05, 0.01]
cont_moeda = {'0.5': 0, '0.1': 0, '0.05': 0, '0.01': 0}
if resto > 0.00:
for valor in moedas:
while resto >= valor:
str_valor = str(valor)
cont_moeda[str_valor] += 1
resto = round(resto, 2) - valor
break
return cont_moeda
return cont_moeda
我嘗試使用 round(resto, 2)、round(resto, 10) 和 Decimal(resto),但結果還是錯誤的。 當我傳遞一個值0.15時,使用resto = round(resto, 2) - valor
valor 結果是0.04999999999999999 。
使用 Decimal 的結果是:
我怎樣才能圍繞這個數字,使四舍五入的數字為 0.05?
您可以使用:
resto = round(resto - valor, 2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.