Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中用2浮点表示值浮点?_Python_Floating - Fatal编程技术网

如何在python中用2浮点表示值浮点?

如何在python中用2浮点表示值浮点?,python,floating,Python,Floating,我需要计算float类型的值,因此,在python中,0.01不是0.01,而是0.100000000000001+一些数字(由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 rest

我需要计算float类型的值,因此,在python中,0.01不是0.01,而是0.100000000000001+一些数字(由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.15时,结果为0.04999999999

使用十进制,结果为:

如何将该数字舍入为0.05?

您可以使用:

resto = round(resto - valor, 2)

这回答了你的问题吗?