简体   繁体   English

在 Python 中指定小数位数

[英]Specifying number of decimal places in Python

When accepting user input with a decimal in Python I'm using:在 Python 中接受带有小数的用户输入时,我正在使用:

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

which returns exactly what is entered - say $43.45它返回输入的内容 - 说 $43.45
but when using that value to calculate and display tax I'm using:但是当使用该值来计算和显示税收时,我正在使用:

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

which returns a display of $ 2.607 using使用返回 $2.607 的显示

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

How can I set that to $2.61 instead?我该如何将其设置为 2.61 美元?
Forgive me, I realize this is basic stuff but they don't call it Intro for nothing...原谅我,我意识到这是基本的东西,但他们不会无缘无故地称之为介绍......

Thanks!谢谢!

There's a few ways to do this depending on how you want to hold the value.有几种方法可以做到这一点,具体取决于您希望如何保持价值。

You can use basic string formatting, eg您可以使用基本的字符串格式,例如

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

You can modify the 2 to whatever precision you need.您可以将2修改为您需要的任何精度。

However, since you're dealing with money you should look into the decimal module which has a cool method named quantize which is exactly for working with monetary applications.但是,由于您正在处理货币,因此您应该查看小数模块,该模块具有一个名为quantize的很酷的方法,该方法完全适用于货币应用程序。 You can use it like so:你可以像这样使用它:

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

Note that the rounding attribute is purely optional as well.请注意, rounding属性也是完全可选的。

I'm astonished by the second number you mention (and confirm by your requested rounding) -- at first I thought my instinct for mental arithmetic was starting to fail me (I am getting older, after all, so that might be going the same way as my once-sharp memory!-)... but then I confirmed it hasn't, yet, by using, as I imagine you are, Python 3.1, and copying and pasting..:我被你提到的第二个数字(并确认由您所要求的四舍五入)震惊-起初我还以为我的心算本能已开始令我失望(年纪越来越大,毕竟,这样可能会相同作为我曾经清晰的记忆!-)...但后来我确认它还没有,正如我想象的那样,通过使用 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
>>> 

...as expected -- yet, you say it instead "returns a display of $ 2.607"... which might be a typo, just swapping two digits, except that you then ask "How can I set that to $2.61 instead?" ......正如预期的那样——然而,你说它“返回 2.607 美元的显示”......这可能是一个错字,只是交换了两位数字,除了你问“我如何将其设置为 2.61 美元? ” so it really seems you truly mean 2.607 (which might be rounded to 2.61 in various ways) and definitely not the arithmetically correct result, 2.067 (which at best might be rounded to 2.07... definitely not to 2.61 as you request).所以看起来你真的是指2.607 (可能以各种方式四舍五入到 2.61),绝对不是算术上正确的结果, 2.067 (最多可能四舍五入到 2.07……绝对不是你要求的 2.61)。

I imagine you first had the typo occur in transcription, and then mentally computed the desired rounding from the falsified-by-typo 2.607 rather than the actual original result -- is that what happened?我想您首先在转录中出现错字,然后根据错字错误2.607而不是实际的原始结果在心里计算出所需的舍入——是这样吗? It sure managed to confuse me for a while!-)它确实让我困惑了一段时间!-)

Anyway, to round a float to two decimal digits, simplest approach is the built-in function round with a second argument of 2 :无论如何,要将浮点数四舍五入为两位十进制数字,最简单的方法是使用第二个参数为2的内置函数round

>>> round(2.067, 2)
2.07
>>> round(2.607, 2)
2.61

For numbers exactly equidistant between two possibilities, it rounds-to-even:对于两个可能性之间完全等距的数字,它四舍五入到偶数:

>>> round(2.605, 2)
2.6
>>> round(2.615, 2)
2.62

or, as the docs put it (exemplifying with the single-argument form of round , which rounds to the closest integer):或者,正如文档所说的那样(以单参数形式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).如果两个倍数相等,则向偶数选择舍入(例如,round(0.5) 和 round(-0.5) 均为 0,而 round(1.5) 为 2)。

However, for computations on money, I second the recommendation, already given in other answers, to stick with what the decimal module offers, instead of float numbers.但是,对于货币计算,我支持其他答案中已经给出的建议,坚持使用小数模块提供的内容,而不是float

You don't show the code for display_data , but here's what you need to do:您没有显示display_data的代码,但您需要执行以下操作:

print "$%0.02f" %amount

This is a format specifier for the variable amount .这是变量amount格式说明符

Since this is beginner topic, I won't get into floating point rounding error , but it's good to be aware that it exists.由于这是初学者主题,我不会进入浮点舍入错误,但很高兴知道它存在。

To calculate tax, you could use round (after all, that's what the restaurant does):要计算税收,您可以使用round (毕竟,这就是餐厅所做的):

def calc_tax(mealPrice):  
    tax = round(mealPrice*.06,2)
    return tax

To display the data, you could use a multi-line string, and thestring format method :要显示数据,您可以使用多行字符串和字符串格式方法

def display_data(mealPrice, tax):
    total=round(mealPrice+tax,2)
    print('''\
Your Meal Price is {m:=5.2f}
Tax                {x:=5.2f}
Total              {t:=5.2f}
'''.format(m=mealPrice,x=tax,t=total))

Note the format method was introduced in Python 2.6, for earlier versions you'll need to use old-style string interpolation % :请注意 format 方法是在 Python 2.6 中引入的,对于早期版本,您需要使用旧式字符串插值%

    print('''\
Your Meal Price is %5.2f
Tax                %5.2f
Total              %5.2f
'''%(mealPrice,tax,total))

Then然后

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

yields:产量:

# Enter the meal subtotal: $43.45
# Your Meal Price is 43.45
# Tax                 2.61
# Total              46.06

This standard library solution likely has not been mentioned because the question is so dated.这个标准库解决方案可能没有被提及,因为这个问题已经过时了。 While these answers may scale to the other use cases beyond currency where differing levels of decimals are required, it seems you need it for currency.虽然这些答案可能适用于需要不同级别小数的货币以外的其他用例,但似乎您需要它来处理货币。

I recommend you use the standard library locale.currency object.我建议您使用标准库locale.currency对象。 It seems to have been created to address this problem of currency representation.它似乎是为了解决货币代表的这个问题而创建的。

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

locale.currency(1.23)
>>>'$1.23'
locale.currency(1.53251)
>>>'$1.23'
locale.currency(1)
>>>'$1.00'

locale.currency(mealPrice)

Currency generalizes to other countries as well.货币也适用于其他国家。

Use round() function.使用 round() 函数。

round(2.607) = 3
round(2.607,2) = 2.61

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM