Rounding up with pennies in Python?

后端 未结 5 1736
夕颜
夕颜 2020-12-19 20:46

I am making a change program in python. The user must input a dollar amount and then the program will calculate the change in twenties, tens, fives, ones, quarters, dimes, n

相关标签:
5条回答
  • 2020-12-19 21:31

    The problems you are having are a result of imprecise floating-point arithmetic. There is no way to precisely represent 0.01 in IEEE floating point. That is one reason not to use floats when working with currency.

    You should use decimals or even integers, because you know there are at most 2 digits after the decimal point. In that case, just work with the amount in pennies.


    On the problem itself, I think the easiest way to do it is convert your amount in dollars to the amount in pennies, then iterate through a predefined list of values containing listing the equivalent amount of pennies (in descending order) for each denomination:

    def change(amount):
    
        # this can be removed if you pass the amount in pennies
        # rather than dollars
        amount = int(round(amount*100))
    
        values = [2000, 1000, 500, 100, 25, 10, 5, 1]
        denom = ['twenties', 'tens', 'fives', 'ones', 'quarters', 'dimes', 'nickels', 'pennies']
    
        for i in range(len(values)):
            num = amount / values[i]
            amount -= num * values[i]
            print str(num) + " " + denom[i]
    

    Now calling change(58.79) will print

    2 twenties
    1 tens
    1 fives
    3 ones
    3 quarters
    0 dimes
    0 nickels
    4 pennies
    

    As seen on codepad.org

    0 讨论(0)
  • 2020-12-19 21:32

    The problem is that 0.01 cannot be accurately represented as a binary floating point value (which is how normal floats are stored – this is true for any language, not just Python). So if you need exact values for dollars and cents, you can use the decimal module. That way you can be sure that your values will be rounded exactly.

    Or (since Decimals might be overkill here), first multiply every dollar value by 100 (this is not the same as dividing by 0.01 for the above reasons!), convert to int, do your calculations, and divide by 100.

    0 讨论(0)
  • 2020-12-19 21:37
    >>> from math import ceil
    >>> a = 58.79
    >>> ceil(a % 0.05 * 100)
    4.0
    >>>
    

    [edit]

    Now that I think of it, might aswell just go with

    >>> a = 58.79
    >>> a*100 % 5
    4.0
    
    0 讨论(0)
  • 2020-12-19 21:50

    use the decimal package

    http://docs.python.org/library/decimal.html

    it is meant exactly for this kind of use case

    0 讨论(0)
  • 2020-12-19 21:51

    Multiply the user's inputed dollar value by 100, convert to int, and work in units of pennies.

    Integer arithmetic is dead simple (and exact). Floating point arithmetic is tricky and forces you to use more brain cells :) . Save brain cells and work entirely in ints.

    0 讨论(0)
提交回复
热议问题