我对你提到的第二个数字感到惊讶(并通过你要求的四舍五入来证实)——起初我以为我的心算本能开始让我失望了(毕竟,我的年龄越来越大了,所以这可能和我曾经敏锐的记忆一样!-)... 但后来我证实了它还没有,正如我想象的那样,使用Python 3.1,复制和粘贴>>> def input_meal():
... mealPrice = input('Enter the meal subtotal: $')
... mealPrice = float (mealPrice)
... return mealPrice
...
>>> def calc_tax(mealPrice):
... tax = mealPrice*.06
... return tax
...
>>> m = input_meal()
Enter the meal subtotal: $34.45
>>> print(calc_tax(m))
2.067
>>>
……正如预期的——但是,你说它“返回2.607美元的显示”。。。可能是打字错误,只是换了两个数字,除了你问“我怎么能改成2.61美元?”所以看起来你真正的意思是2.607(可能以各种方式四舍五入到2.61),而绝对不是算术上正确的结果,2.067(最多可能四舍五入到2.07。。。绝对不会按照您的要求将设置为到2.61)。
我想你先是在抄写中出现了错别字,然后在心理上从错别字所伪造的2.607而不是实际的原始结果中计算出所需的四舍五入——是这样吗?我真是一时糊涂了!-)
无论如何,要将一个浮点数舍入到两个十进制数字,最简单的方法是内置函数round,第二个参数为2:>>> round(2.067, 2)
2.07
>>> round(2.607, 2)
2.61
对于两种可能性之间完全相等的数字,它会舍入为偶数:>>> round(2.605, 2)
2.6
>>> round(2.615, 2)
2.62
或者,正如文档所说(以round的单参数形式为例,该形式舍入到最接近的整数):if two multiples are equally close, rounding is done toward the
even choice (so, for example, both
round(0.5) and round(-0.5) are 0, and
round(1.5) is 2).
然而,对于金钱计算,我支持其他答案中已经给出的建议,即坚持decimal模块提供的内容,而不是float数字。