Python 将逗号添加到数字字符串中 [英] Python Add Comma Into Number String

查看:48
本文介绍了Python 将逗号添加到数字字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Python v2,我的程序运行了一个值最后给出一个四舍五入到小数点后两位的数字:

Using Python v2, I have a value running through my program that puts out a number rounded to 2 decimal places at the end:

像这样:

print ("Total cost is: ${:0.2f}".format(TotalAmount))

有没有办法在小数点左边每 3 位插入一个逗号值?

Is there a way to insert a comma value every 3 digits left of the decimal point?

即:10000.00 变为 10,000.00 或 1000000.00 变为 1,000,000.00

Ie: 10000.00 becomes 10,000.00 or 1000000.00 becomes 1,000,000.00

感谢您的帮助.

推荐答案

在 Python 2.7 和 3.x 中,您可以使用格式语法 :,

In Python 2.7 and 3.x, you can use the format syntax :,

>>> total_amount = 10000
>>> print("{:,}".format(total_amount))
10,000

>>> print("Total cost is: ${:,.2f}".format(total_amount))
Total cost is: $10,000.00

这记录在 PEP 378 -- 千位分隔符的格式说明并在 官方文档使用逗号作为千位分隔符"中有一个示例;

这篇关于Python 将逗号添加到数字字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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