如何格式化小数以始终显示小数点后 2 位?
我想显示:
49
为49.00
和:
54.9
为54.90
无论小数长度或是否有小数位,我想显示一个有 2 位小数的 Decimal
,并且我想以有效的方式做到这一点。目的是显示金钱价值。
例如,4898489.00
对于内置float
类型的类似问题,请参阅将浮点数限制为小数点后两位。
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
For the analogous issue with the built-in float
type, see Limiting floats to two decimal points.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
您应该使用 新的格式规范来定义如何表示您的值:
该文档有时可能有点迟钝,因此我推荐以下更易于阅读的参考:
.format()
字符串格式%
字符串格式与新式.format()
字符串格式化Python 3.6 引入 文字字符串插值(也称为 f-strings),所以现在你可以写更多上面的内容简洁为:
You should use the new format specifications to define how your value should be represented:
The documentation can be a bit obtuse at times, so I recommend the following, easier readable references:
.format()
string formatting%
string formatting with the new-style.format()
string formattingPython 3.6 introduced literal string interpolation (also known as f-strings) so now you can write the above even more succinct as:
的 字符串格式化操作 部分Python 文档包含您正在寻找的答案。简而言之:
一些例子:
The String Formatting Operations section of the Python documentation contains the answer you're looking for. In short:
Some examples:
我想您可能正在使用
来自
十进制
模块? (如果您需要任意大数字的小数点后精确两位数的精度,那么您绝对应该这样做,这就是您的问题标题所暗示的......)如果是这样,则 Decimal FAQ 文档部分有一个问题/答案对这可能对你有用:
下一个问题是
如果您需要答案(以及许多其他有用的信息),请参阅 文档的上述部分。另外,如果您将
Decimal
保留为小数点以外两位数的精度(意味着将所有数字保留在小数点左侧和小数点右侧两位数所需的精度)就这样了……),然后用str
将它们转换为字符串就可以正常工作:I suppose you're probably using the
Decimal()
objects from thedecimal
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:
The next question reads
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 withstr
will work fine:您可以将
2f
中的2
更改为您想要显示的任意位数的小数点。编辑:
从
Python3.6
,这转换为:You can change
2
in2f
to any number of decimal points you want to show.EDIT:
From
Python3.6
, this translates to:您可以使用字符串格式化运算符 因此:
我不确定你所说的“高效”是什么意思——这几乎肯定不是你的应用程序的瓶颈。如果您的程序运行缓慢,请首先对其进行分析以找到热点,然后对其进行优化。
You can use the string formatting operator as so:
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.
.format 是一种更易读的处理变量格式的方法:
.format is a more readable way to handle variable formatting:
在 python 3 中,这样做的一种方法是
In python 3, a way of doing this would be
OP 总是希望显示两位小数,因此像所有其他答案一样显式调用格式化函数还不够好。
正如其他人已经指出的那样,
Decimal
对于货币来说效果很好。但是Decimal
显示所有小数位。因此,覆盖其显示格式化程序:用法:
简单。
编辑:
要显示至少两位小数,但不截断有效数字:
我希望Python的未来版本能够改进数字格式以允许最小小数位。类似于 Excel 数字格式中的
#
符号。The OP always wants two decimal places displayed, so explicitly calling a formatting function, as all the other answers have done, is not good enough.
As others have already pointed out,
Decimal
works well for currency. ButDecimal
shows all the decimal places. So, override its display formatter:Usage:
Simple.
EDIT:
To display at least two decimal places but without truncating significant digits:
I hope that a future version of Python will improve the number formatting to allow minimum decimal places. Something like the
#
sign in Excel's number formatting.如果你有多个参数,你可以使用
if you have multiple parameters you can use
如果您将其用于货币,并且还希望该值由
,
分隔,您可以使用$ {:,.f2}.format(currency_value)
。例如:
currency_value = 1234.50
$ {:,.f2}.format(currency_value)
-->
< code>$ 1,234.50这是我前段时间写的一些代码:
print("> 年底 " +year_string + " 支付的总金额为 \t$ {:,.2f} “.format(total_paid))
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))
这与您可能已经看到的解决方案相同,但通过这种方式,它会更清晰:
>>> num = 3.141592654
>>>> print(f"数字:{num:.2f}")
This is the same solution as you have probably seen already, but by doing it this way it's more clearer:
>>> num = 3.141592654
>>> print(f"Number: {num:.2f}")
向您展示如何执行此操作的最简单方法示例是:
代码:
>>>点 = 19.5
<代码>>>总计 = 22
>>>'正确答案:{:.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%
如果您有 Decimal 对象,最简单的方法是将 quantize 用作:
if you have a Decimal object the easiest way is to use quantize as:
怎么样
what about