如何在 python 中以 2 个浮点数表示浮点数?
How to represent values float in 2 float point in python?
我需要计算 float 类型的值,因此,在 python 中,0.01 不是 0.01,而是 0.10000000000000001 + 一些数字(由 python 文档 Floating 引用)。
好的,我的函数需要计算每个值的硬币数量。
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),结果还是不对。
使用 resto = round(resto, 2) - valor
结果是 0.04999999999999999 当我传递值 0.15.
使用十进制结果是:
Image for Decimal module
如何绕过这个数字,使四舍五入后的数字为 0.05?
您可以使用:
resto = round(resto - valor, 2)
我需要计算 float 类型的值,因此,在 python 中,0.01 不是 0.01,而是 0.10000000000000001 + 一些数字(由 python 文档 Floating 引用)。
好的,我的函数需要计算每个值的硬币数量。
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),结果还是不对。
使用 resto = round(resto, 2) - valor
结果是 0.04999999999999999 当我传递值 0.15.
使用十进制结果是:
Image for Decimal module
如何绕过这个数字,使四舍五入后的数字为 0.05?
您可以使用:
resto = round(resto - valor, 2)