Python:.format()未正确舍入

2024-09-26 22:07:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两张单子:

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。你知道吗

是我做错了什么,还是方法、格式本身有问题?你知道吗


Tags: 方法informatfor格式价格单子end
1条回答
网友
1楼 · 发布于 2024-09-26 22:07:32

你的问题是:

14.95 - (0.1 * 14.95) = 13.455

不,在IEEE doubles中,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的二进制分数,您可能希望使用^{}而不是float。当然Decimal也是不精确的,但是最接近14.95的小数点显然是14.95。:)

相关问题 更多 >

    热门问题