指定Python中的小数位数

2024-05-18 20:54:33 发布

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

在Python中接受十进制用户输入时,我使用:

#will input meal subtotal  
def input_meal():  
    mealPrice = input('Enter the meal subtotal: $')  
    mealPrice = float (mealPrice)  
    return mealPrice  

返回输入的内容-比如$43.45
但是,当使用该值计算和显示税款时,我使用的是:

#will calculate 6% tax  
def calc_tax(mealPrice):  
    tax = mealPrice*.06  
    return tax

使用返回$2.607的显示

mealPrice = input_meal()
tax = calc_tax(mealPrice)
display_data(mealPrice, tax)  

我怎么能改成2.61美元呢?
原谅我,我意识到这是最基本的东西,但他们不叫它介绍白费。。。

谢谢!


Tags: the用户内容inputreturndefcalcfloat
3条回答

您不显示display_data的代码,但需要执行以下操作:

print "$%0.02f" %amount

这是变量amountformat specifier

因为这是一个初学者的话题,所以我不会进入floating point rounding error,但是很好地意识到它的存在。

有几种方法可以做到这一点,具体取决于您希望如何保存值。

可以使用基本字符串格式,例如

'Your Meal Price is %.2f' %  mealPrice

您可以将2修改为所需的任何精度。

但是,既然您是在处理钱,那么应该查看decimal模块,该模块有一个很酷的方法,名为quantize,它正好用于处理货币应用程序。你可以这样使用它:

from decimal import Decimal, ROUND_DOWN
mealPrice = Decimal(str(mealPrice)).quantize(Decimal('.01'), rounding=ROUND_DOWN)

注意,rounding属性也是纯可选的。

我对你提到的第二个数字感到惊讶(并通过你要求的四舍五入来证实)——起初我以为我的心算本能开始让我失望了(毕竟,我的年龄越来越大了,所以这可能和我曾经敏锐的记忆一样!-)... 但后来我证实了它还没有,正如我想象的那样,使用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数字。

相关问题 更多 >

    热门问题