如何将整数转换为逗号分隔的字符串

时间:2022-04-08 00:17:37

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".

我的银行余额为1000000,但当我在屏幕上显示时,我希望它读作“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.

现在有一些方法可以解决这个问题,只需将其设置为“1,000,000”,然后在需要使用整数值时将其标记为逗号并将其转换为整数。但我不想这样做。

bankBalance = 1000000

3 个解决方案

#1


14  

Use format:

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

#2


3  

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

使用str.format或format作为格式说明符:

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

#3


2  

Using format:

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

#1


14  

Use format:

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

#2


3  

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

使用str.format或format作为格式说明符:

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

#3


2  

Using format:

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