简体   繁体   中英

Is there a way to round up or down a string to 5?

I'm building a program where it takes the final price of many items and then rounds it up or down depending on the last digit. For strings ending in 0,1,2,5,8,9 this works fine. But I need to round strings that end in 3,4,6,7 up/down to 5. How would I go about doing this?

Current code:


if str(finalTotalPrice).endswith(("1" , "2")) :
    roundedDown = round(finalTotalPrice, 1)
    print("Final Total = $" + str(roundedDown) + str(0))
    print()
    
    cashPayment = float( input("How much cash will you pay with? $"))
    change = (cashPayment - roundedDown)
    change = round(change, 3)
    print("Your change is $" + str(change))

elif str(finalTotalPrice).endswith(("3", "4")) :


elif str(finalTotalPrice).endswith(("6" , "7")) :
    

elif str(finalTotalPrice).endswith(("8" , "9")) :
    roundedUp = round(finalTotalPrice, 1)
    print("Final Total = $" + str(roundedUp) + str(0))
    print()

    cashPayment = float( input("How much cash will you pay with? $"))
    change = (cashPayment - roundedUp)
    change = round(change, 3)
    print("Your change is $" + str(change))

elif str(finalTotalPrice).endswith(("5" , "0")) :
    print("Final Total = $" + str(finalTotalPrice))
    print()

    cashPayment = float( input("How much cash will you pay with? $"))
    change = (cashPayment - finalTotalPrice)
    change = round(change, 3)
    print("Your change is $" + str(change))

You could do something like this:

def round5(n):
   return str(round(int(value) / 5.0) * 5)

value = "123"
print(round5(value)) #==> 125

value = "357"
print(round5(value)) #==> 355

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM