2015-05-02 38 views
-2

我有这两个名单:的Python:.format()不正确四舍五入

salePrices = [9.95, 14.95, 19.95, 24.95, 29.95, 34.95, 39.95, 44.95, 49.95] 
percents = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50] 

,然后使用这个for循环中,我通过每个迭代百分比并计算折扣价。

for percent in percents: 

    for salePrice in salePrices: 
     newPrice = salePrice - ((percent/100) * salePrice) 
     print("\t" + "{0:.2f}".format(newPrice), end = " ") 
    print() 

这一切工作正常,除了一个问题:一些计算值不能正确舍入。

例如,14.95 - (0.1 * 14.95)= 13.455,应该用.format()四舍五入为13.46。但是,打印的值是13.45。

有什么我做错了,或者它是方法,格式本身的问题?

+0

尝试之前舍入.format? – Tarik

回答

3

这是你的问题:

14.95 - (0.1 * 14.95) = 13.455 

没有,在IEEE双打,14.95 - (0.1 * 14.95)13.454999999999998。正确地向下舍入到13.45

Here's the obligatory link to What Every Computer Scientist Should Know About Floating-Point Arithmetic

如果你想14.95实际上是完全14.95,而不是最近的二进制小数到14.95,您可能需要使用Decimal而不是float。当然Decimal也是不精确的,但最接近14.95的小数部分显然确实是14.95。 :)

+0

甜,谢谢你:) – user2681474

+0

SO提问者==计算机科学家。大声笑 – Barmar

+0

@Barmar:嗨,当那些不是计算机科学家的人无法使用带FPU的计算机时,这篇文章就被写回来了。 :) – abarnert