问题:如何设置小数位格式以始终显示2个小数位?
我要显示:
49
如 49.00
和:
54.9
如 54.90
不管小数长度或是否有小数位,我都希望显示一个Decimal
带有2个小数位的a,并且我想以一种有效的方式来做到这一点。目的是显示货币值。
例如, 4898489.00
I want to display:
49
as 49.00
and:
54.9
as 54.90
Regardless of the length of the decimal or whether there are are any decimal places, I would like to display a Decimal
with 2 decimal places, and I’d like to do it in an efficient way. The purpose is to display money values.
eg, 4898489.00
回答 0
我想您可能正在使用模块中的Decimal()
对象decimal
?(如果您需要精确到小数点后两位精确到两位数且任意大的数字,那么绝对应该如此,这就是您的问题标题所暗示的……)
如果是这样,文档的“ 十进制常见问题解答”部分将包含一个问题/答案对,这可能对您有用:
问:在具有两位小数位的定点应用程序中,某些输入有很多位,需要四舍五入。其他人不应有多余的数字,需要进行验证。应该使用什么方法?
答:Quantize()方法将舍入到固定数量的小数位数。如果设置了不精确陷阱,则它对于验证也很有用:
>>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')
>>> # Validate that a number does not exceed two places
>>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Decimal('3.21')
>>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Traceback (most recent call last):
...
Inexact: None
下一个问题是
问:一旦有了有效的两个位置输入,如何在整个应用程序中保持不变?
如果您需要答案(以及许多其他有用的信息),请参阅docs的上述部分。另外,如果您将Decimal
s的精度保持在小数点后两位(这意味着要使所有数字保持在小数点的左边,而使所有数字保持在小数点的右边,并且不多…),然后将它们转换为str
可以正常工作:
str(Decimal('10'))
# -> '10'
str(Decimal('10.00'))
# -> '10.00'
str(Decimal('10.000'))
# -> '10.000'
I suppose you’re probably using the Decimal()
objects from the decimal
module? (If you need exactly two digits of precision beyond the decimal point with arbitrarily large numbers, you definitely should be, and that’s what your question’s title suggests…)
If so, the Decimal FAQ section of the docs has a question/answer pair which may be useful for you:
Q. In a fixed-point application with two decimal places, some inputs have many places and need to be rounded. Others are not supposed to have excess digits and need to be validated. What methods should be used?
A. The quantize() method rounds to a fixed number of decimal places. If the Inexact trap is set, it is also useful for validation:
>>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')
>>> # Validate that a number does not exceed two places
>>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Decimal('3.21')
>>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Traceback (most recent call last):
...
Inexact: None
The next question reads
Q. Once I have valid two place inputs, how do I maintain that invariant throughout an application?
If you need the answer to that (along with lots of other useful information), see the aforementioned section of the docs. Also, if you keep your Decimal
s with two digits of precision beyond the decimal point (meaning as much precision as is necessary to keep all digits to the left of the decimal point and two to the right of it and no more…), then converting them to strings with str
will work fine:
str(Decimal('10'))
# -> '10'
str(Decimal('10.00'))
# -> '10.00'
str(Decimal('10.000'))
# -> '10.000'
回答 1
您应该使用新的格式规范来定义应如何表示值:
>>> from math import pi # pi ~ 3.141592653589793
>>> '{0:.2f}'.format(pi)
'3.14'
该文档有时可能有点晦涩难懂,所以我建议您使用以下更容易阅读的参考文献:
Python 3.6引入了文字字符串插值(也称为f字符串),因此现在您可以将上面的内容写得更简洁:
>>> f'{pi:.2f}'
'3.14'
You should use the new format specifications to define how your value should be represented:
>>> from math import pi # pi ~ 3.141592653589793
>>> '{0:.2f}'.format(pi)
'3.14'
The documentation can be a bit obtuse at times, so I recommend the following, easier readable references:
Python 3.6 introduced literal string interpolation (also known as f-strings) so now you can write the above even more succinct as:
>>> f'{pi:.2f}'
'3.14'
回答 2
Python文档的“ 字符串格式操作”部分包含您要寻找的答案。简而言之:
"%0.2f" % (num,)
一些例子:
>>> "%0.2f" % 10
'10.00'
>>> "%0.2f" % 1000
'1000.00'
>>> "%0.2f" % 10.1
'10.10'
>>> "%0.2f" % 10.120
'10.12'
>>> "%0.2f" % 10.126
'10.13'
The String Formatting Operations section of the Python documentation contains the answer you’re looking for. In short:
"%0.2f" % (num,)
Some examples:
>>> "%0.2f" % 10
'10.00'
>>> "%0.2f" % 1000
'1000.00'
>>> "%0.2f" % 10.1
'10.10'
>>> "%0.2f" % 10.120
'10.12'
>>> "%0.2f" % 10.126
'10.13'
回答 3
您可以这样使用字符串格式运算符:
num = 49
x = "%.2f" % num # x is now the string "49.00"
我不确定“高效”是什么意思-几乎可以肯定这不是应用程序的瓶颈。如果您的程序运行缓慢,请先对其进行分析,以找到热点,然后对其进行优化。
You can use the string formatting operator as so:
num = 49
x = "%.2f" % num # x is now the string "49.00"
I’m not sure what you mean by “efficient” — this is almost certainly not the bottleneck of your application. If your program is running slowly, profile it first to find the hot spots, and then optimize those.
回答 4
>>> print "{:.2f}".format(1.123456)
1.12
您可以更改2
在2f
任意数量的要显示小数点。
编辑:
从Python3.6
,这意味着:
>>> print(f"{1.1234:.2f}")
1.12
>>> print "{:.2f}".format(1.123456)
1.12
You can change 2
in 2f
to any number of decimal points you want to show.
EDIT:
From Python3.6
, this translates to:
>>> print(f"{1.1234:.2f}")
1.12
回答 5
.format是处理变量格式的更易读的方法:
'{:.{prec}f}'.format(26.034, prec=2)
.format is a more readable way to handle variable formatting:
'{:.{prec}f}'.format(26.034, prec=2)
回答 6
在python 3中,一种方法是
'{:.2f}'.format(number)
In python 3, a way of doing this would be
'{:.2f}'.format(number)
回答 7
如果您有多个参数,则可以使用
print('some string {0:.2f} & {1:.2f}'.format(1.1234,2.345))
>>> some string 1.12 & 2.35
if you have multiple parameters you can use
print('some string {0:.2f} & {1:.2f}'.format(1.1234,2.345))
>>> some string 1.12 & 2.35
回答 8
如果您将其用作货币,并且还希望将值与分隔,则,
可以使用
$ {:,.f2}.format(currency_value)
。
例如:
currency_value = 1234.50
$ {:,.f2}.format(currency_value)
-->
$ 1,234.50
这是我前一段时间写的一些代码:
print("> At the end of year " + year_string + " total paid is \t$ {:,.2f}".format(total_paid))
> At the end of year 1 total paid is $ 43,806.36
> At the end of year 2 total paid is $ 87,612.72
> At the end of year 3 total paid is $ 131,419.08
> At the end of year 4 total paid is $ 175,225.44
> At the end of year 5 total paid is $ 219,031.80 <-- Note .80 and not .8
> At the end of year 6 total paid is $ 262,838.16
> At the end of year 7 total paid is $ 306,644.52
> At the end of year 8 total paid is $ 350,450.88
> At the end of year 9 total paid is $ 394,257.24
> At the end of year 10 total paid is $ 438,063.60 <-- Note .60 and not .6
> At the end of year 11 total paid is $ 481,869.96
> At the end of year 12 total paid is $ 525,676.32
> At the end of year 13 total paid is $ 569,482.68
> At the end of year 14 total paid is $ 613,289.04
> At the end of year 15 total paid is $ 657,095.40 <-- Note .40 and not .4
> At the end of year 16 total paid is $ 700,901.76
> At the end of year 17 total paid is $ 744,708.12
> At the end of year 18 total paid is $ 788,514.48
> At the end of year 19 total paid is $ 832,320.84
> At the end of year 20 total paid is $ 876,127.20 <-- Note .20 and not .2
If you’re using this for currency, and also want the value to be seperated by ,
‘s you can use
$ {:,.f2}.format(currency_value)
.
e.g.:
currency_value = 1234.50
$ {:,.f2}.format(currency_value)
-->
$ 1,234.50
Here is a bit of code I wrote some time ago:
print("> At the end of year " + year_string + " total paid is \t$ {:,.2f}".format(total_paid))
> At the end of year 1 total paid is $ 43,806.36
> At the end of year 2 total paid is $ 87,612.72
> At the end of year 3 total paid is $ 131,419.08
> At the end of year 4 total paid is $ 175,225.44
> At the end of year 5 total paid is $ 219,031.80 <-- Note .80 and not .8
> At the end of year 6 total paid is $ 262,838.16
> At the end of year 7 total paid is $ 306,644.52
> At the end of year 8 total paid is $ 350,450.88
> At the end of year 9 total paid is $ 394,257.24
> At the end of year 10 total paid is $ 438,063.60 <-- Note .60 and not .6
> At the end of year 11 total paid is $ 481,869.96
> At the end of year 12 total paid is $ 525,676.32
> At the end of year 13 total paid is $ 569,482.68
> At the end of year 14 total paid is $ 613,289.04
> At the end of year 15 total paid is $ 657,095.40 <-- Note .40 and not .4
> At the end of year 16 total paid is $ 700,901.76
> At the end of year 17 total paid is $ 744,708.12
> At the end of year 18 total paid is $ 788,514.48
> At the end of year 19 total paid is $ 832,320.84
> At the end of year 20 total paid is $ 876,127.20 <-- Note .20 and not .2
回答 9
向您展示如何做到这一点的最简单方法示例是:
代码:
>>> points = 19.5
>>> total = 22
>>>'Correct answers: {:.2%}'.format(points/total)
`
输出:正确答案:88.64%
The Easiest way example to show you how to do that is :
Code :
>>> points = 19.5
>>> total = 22
>>>'Correct answers: {:.2%}'.format(points/total)
`
Output : Correct answers: 88.64%
回答 10
关于什么
print round(20.2564567 , 2) >>>>>>> 20.25
print round(20.2564567 , 4) >>>>>>> 20.2564
what about
print round(20.2564567 , 2) >>>>>>> 20.25
print round(20.2564567 , 4) >>>>>>> 20.2564