<p>我对你提到的第二个数字感到惊讶(并通过你要求的四舍五入来证实)——起初我以为我的心算本能开始让我失望了(毕竟,我的年龄越来越大了,所以这可能和我曾经敏锐的记忆一样!-)... 但后来我证实了它还没有,正如我想象的那样,使用Python 3.1,复制和粘贴</p>
<pre><code>>>> 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
>>>
</code></pre>
<p>……正如预期的——但是,你说它“返回2.607美元的显示”。。。可能是打字错误,只是换了两个数字,除了你问“我怎么能改成2.61美元?”所以看起来你真正的意思是<code>2.607</code>(可能以各种方式四舍五入到2.61),而绝对不是算术上正确的结果,<code>2.067</code>(最多可能四舍五入到2.07。。。绝对不会按照您的要求将<em>设置为</em>到2.61)。</p>
<p>我想你先是在抄写中出现了错别字,然后在心理上从错别字所伪造的<code>2.607</code>而不是实际的原始结果中计算出所需的四舍五入——是这样吗?我真是一时糊涂了!-)</p>
<p>无论如何,要将一个浮点数舍入到两个十进制数字,最简单的方法是内置函数<a href="http://docs.python.org/py3k/library/functions.html?highlight=round#round" rel="noreferrer">round</a>,第二个参数为<code>2</code>:</p>
<pre><code>>>> round(2.067, 2)
2.07
>>> round(2.607, 2)
2.61
</code></pre>
<p>对于两种可能性之间完全相等的数字,它会舍入为偶数:</p>
<pre><code>>>> round(2.605, 2)
2.6
>>> round(2.615, 2)
2.62
</code></pre>
<p>或者,正如文档所说(以<code>round</code>的单参数形式为例,该形式舍入到最接近的整数):</p>
<blockquote>
<p>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).</p>
</blockquote>
<p>然而,对于金钱计算,我支持其他答案中已经给出的建议,即坚持<a href="http://docs.python.org/py3k/library/decimal.html?highlight=decimal#module-decimal" rel="noreferrer">decimal</a>模块提供的内容,而不是<code>float</code>数字。</p>