Programmer XYZ
Programmer XYZ

Reputation: 408

Truncating ints without rounding?

I made this program that takes change and figures out how many full dollars, and leftover change. The way it is setup, it takes the amount of change, 495 for example, and then converts it to dollars, 4.95. Now I want to cut off the .95 and leave the 4, how do I do this without it rounding up to 5? Thanks!

def main():
pennies = int(input("Enter pennies : "))
nickels = int(input("Enter nickels : "))
dimes = int(input("Enter dimes : "))
quarters = int(input("Enter quarters : "))

computeValue(pennies, nickels, dimes, quarters)

def computeValue(p,n,d,q):
print("You entered : ")
print("\tPennies  : " , p)
print("\tNickels  : " , n)
print("\tDimes    : " , d)
print("\tQuarters : " , q)

totalCents = p + n*5 + d*10 + q*25
totalDollars = totalCents / 100
totalDollarsTrunc = int(format(totalDollars, '.0f'))
totalPennies = totalCents - (totalDollarsTrunc * 100)

print("Amount of Change = ", totalDollarsTrunc, "dollars and ", totalPennies ,"cents.")

if totalCents < 100:
    print("Amount not = to $1")
elif totalCents == 100:
    print("You have exactly $1.")
elif totalCents >100:
    print("Amount not = to $1")
else:
    print("Error")

Upvotes: 1

Views: 1618

Answers (3)

volcano
volcano

Reputation: 3582

Function int() will do just that

Upvotes: 2

Xymostech
Xymostech

Reputation: 9850

You probably want to use math.ceil or math.floor to give you the rounding in the direction that you want.

Upvotes: 2

nneonneo
nneonneo

Reputation: 179717

In Python, int() truncates when converting from float:

>>> int(4.95)
4

That said, you can rewrite

totalDollars = totalCents / 100
totalDollarsTrunc = int(format(totalDollars, '.0f'))
totalPennies = totalCents - (totalDollarsTrunc * 100)

using the divmod function:

totalDollars, totalPennies = divmod(totalCents, 100)

Upvotes: 8

Related Questions