A Person
A Person

Reputation: 11

How to round ANY number in python on a certain circumstance

I want it so that it tells you how many packages for hotdogs and buns you need for a party. There are 10 hotdogs in a pack and 8 hotdogs in a pack. What is wrong about this?

HotDogInAPack = 10
BunInAPack = 8

Guests = int(input("How many guests are attending?"))
HotDogsEachGuestWants = int(input("How many hotdogs does each guest 
want?"))
AmountNeeded = Guests * HotDogsEachGuestWants
HotDogPackagesNeededINCOMPLETE = AmountNeeded / HotDogInAPack
BunPackagesNeededINCOMPLETE = AmountNeeded / BunInAPack
if type(HotDogPackagesNeededINCOMPLETE) == float:
    ThereAreHotDogLeftOvers = 1
    HotDogPackagesNeededFLOAT = HotDogPackagesNeededINCOMPLETE + 1
    HotDogPackagesNeeded = (format (HotDogPackagesNeededFLOAT, '.0f'))
    LeftOversHotDog = AmountNeeded % HotDogInAPack
else:
    ThereAreHotDogLeftOvers = 2
if type(BunPackagesNeededINCOMPLETE) == float:
    ThereAreBunLeftOvers = 1
    BunPackagesNeededFLOAT = BunPackagesNeededINCOMPLETE + 1
    BunPackagesNeeded = (format (BunPackagesNeededFLOAT, '.0f'))
    LeftOversBun = AmountNeeded % BunInAPack
else:
    ThereAreBunLeftOvers = 2
if ThereAreHotDogLeftOvers == 1:
    print('You need', HotDogPackagesNeeded, 'hotdog packages and you will 
    have', LeftOversHotDog, 'left over hotdogs.')
else:
    print('You need', HotDogPackagesNeeded, 'hotdog packages and you will 
    have no left over hotdog buns!')
if ThereAreBunLeftOvers == 1:
    print('You need', BunPackagesNeeded, 'hotdog bun packages and you 
    will have', LeftOversBun, 'left over hotdog buns.')
else:
    print('You need', BunPackagesNeeded, 'hotdog bun packages and you 
    will have no left over hotdog buns!')

The math is all wrong! I don't know what I did wrong.

Upvotes: 1

Views: 70

Answers (1)

Adam Smith
Adam Smith

Reputation: 54193

You should consider doing this the other way. Rather than checking after the division whether or not you have a whole number: check to see if the division will result in a whole number using the modulo operator %

if amount_needed % hot_dogs_in_pack == 0:
    hot_dog_packages_needed = amount_needed // hot_dogs_in_pack
else:
    hot_dog_packages_needed = amount_needed // hot_dogs_in_pack + 1  # one more than the floor div

This can in fact be done pretty easily with divmod.

packages, leftovers = divmod(amount_needed, hot_dogs_in_pack)
if leftovers:
    packages += 1
    leftovers = (packages * hot_dogs_in_pack) % amount_needed

Upvotes: 2

Related Questions