user13052453
user13052453

Reputation:

How to represent values float in 2 float point in python?

I need to calculate values of type float, so, in python, 0.01 is not 0.01 but 0.10000000000000001 + some digits (referenced by python documentation Floating).

Ok, my function needs to calculate the number of coins for each value.

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

I tried to use round(resto, 2), round(resto, 10) and Decimal(resto), but the result is wrong yet. Using resto = round(resto, 2) - valor the result is 0.04999999999999999 when I pass a values 0.15.

Using Decimal the result is:

Image for Decimal module

How can I around this number so that the rounded number is 0.05?

Upvotes: 1

Views: 56

Answers (1)

kederrac
kederrac

Reputation: 17322

you can use:

resto = round(resto - valor, 2)

Upvotes: 1

Related Questions