Penny rounding in Python?

I am making a change program in python. The user must enter the amount in dollars, and then the program will calculate the change in twenties, tens, five, four, a quarter, nickel and pennies. I was instructed to use the round function for pennies, because if I enter the amount of $ 58.79, the Program tells me to return 3 pennies when it should be 4. Is there a way to round these pennies?

I know the penny value is 0.01, but python reads this as .100000000001, which I believe is the problem.

Any help is appreciated, here is the section I need to round up:

# get the amount to change from the user

change = input("Please enter the amount to change: $")

print "To make change for $",change,"give the customer back:"

# calculate number of twenties
twenties = int(change/ 20)

print twenties, "twenties"

change = change - twenties *20

# calculate tens
tens = int(change / 10)

print tens, "tens"

change = change - tens *10

#calculate fives
fives = int(change / 5)

print fives, "fives"

change = change - fives *5

#calculate ones
ones = int(change / 1)

print ones, "ones"

change = change - ones * 1

#calculate quarters
quarters = int(change / .25)

print quarters, "quarters"

change = change - quarters * .25

#calculate dimes
dimes = int(change / .10)

print dimes, "dimes"

change = change - dimes * .10

#calculate nickels
nickels = int(change / .05)

print nickels, "nickels"

change = change - nickels * .05

#calculate pennies
pennies = int(change / .01)

print pennies, "pennies"
+3
source share
5 answers

, , . 0.01 IEEE. .

, , 2 . .


, - , , ( ) :

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]

change(58.79)

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

codepad.org

+1

100, int .

( ). :). ints.

+3

, 0.01 ​​ ( float) - , Python). , , . , , .

Or (since Decimals may be redundant here), first multiply each 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.

+2
source

use decimal package

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

this means exactly this use case

+1
source
>>> from math import ceil
>>> a = 58.79
>>> ceil(a % 0.05 * 100)
4.0
>>>

[edit]

Now that I think about it, maybe just go with

>>> a = 58.79
>>> a*100 % 5
4.0
0
source

Source: https://habr.com/ru/post/1763513/


All Articles