在 Python 2 中用逗号分隔符格式化一个数字并四舍五入到 2 个小数位? [英] Format a number with comma separators and round to 2 decimal places in Python 2?

查看:39
本文介绍了在 Python 2 中用逗号分隔符格式化一个数字并四舍五入到 2 个小数位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定这一定是重复的,但我找不到关于 SO 的明确答案.

I'm sure this must be a duplicate but I can't find a clear answer on SO.

如何在 Python 2 中将 2083525.34561 输出为 2,083,525.35?

How do I output 2083525.34561 as 2,083,525.35 in Python 2?

我知道:

"{0:,f}".format(2083525.34561)

输出逗号但不舍入.并且:

which outputs commas but does not round. And:

"%.2f" % 2083525.34561

舍入,但不添加逗号.

which rounds, but does not add commas.

推荐答案

添加带有位数的小数点 .2f 参见文档:https://docs.python.org/2/library/string.html#format-specification-mini-language :

Add a decimal point with number of digits .2f see the docs: https://docs.python.org/2/library/string.html#format-specification-mini-language :

In [212]:
"{0:,.2f}".format(2083525.34561)

Out[212]:
'2,083,525.35'

对于python 3,您可以使用f-strings(感谢@亚历克斯 F):

For python 3 you can use f-strings (thanks to @Alex F):

In [2]:
value = 2083525.34561
f"{value:,.2f}"


Out[2]:
'2,083,525.35'

这篇关于在 Python 2 中用逗号分隔符格式化一个数字并四舍五入到 2 个小数位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆