How to convert an integer to a comma separated string

こ雲淡風輕ζ 提交于 2020-01-12 18:57:06

问题


I'm currently working on a program and I've run into a problem.

I have a bank balance of 1000000 but when I display it on the screen I want it to read as "1,000,000".

Now there are ways of getting around this simply by having it set to "1,000,000" and then striping it of commas and converting it to an integer when I need to use the integer value. But I don't want to do that.

bankBalance = 1000000

回答1:


Use format:

>>> bankBalance = 1000000
>>> format(bankBalance, ",")
'1,000,000'
>>>



回答2:


Using str.format or format with , as format specifier:

>>> '{:,}'.format(12345)
'12,345'
>>> format(12345, ',')
'12,345'



回答3:


Using format:

>>> "{:,}".format(1000000)
'1,000,000'


来源:https://stackoverflow.com/questions/20686629/how-to-convert-an-integer-to-a-comma-separated-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!