在没有舍入的情况下截断整数?

时间:2012-10-26 01:26:05

标签: python floating-point python-3.x truncate

我制作了这个程序,需要改变,并计算出多少全部美元和剩余的变化。它的设置方式,它需要更改量,例如495,然后将其转换为美元,4.95。现在我想切断.95然后离开4,如果没有它,我怎么做呢?谢谢!

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")

3 个答案:

答案 0 :(得分:8)

在Python中,int()在从float转换时会截断:

>>> int(4.95)
4

那就是说,你可以改写

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

使用divmod函数:

totalDollars, totalPennies = divmod(totalCents, 100)

答案 1 :(得分:2)

您可能希望使用math.ceilmath.floor为您提供所需方向的舍入。

答案 2 :(得分:2)

函数 int()将只执行