更新:此代码现在同时支持int
和float
数字!
您可以自己编写一些数字到字符串的转换函数,如下所示:
def special_format(n):
s, *d = str(n).partition(".")
r = ",".join([s[x-2:x] for x in range(-3, -len(s), -2)][::-1] + [s[-3:]])
return "".join([r] + d)
使用简单:
print(special_format(1))
print(special_format(12))
print(special_format(123))
print(special_format(1234))
print(special_format(12345))
print(special_format(123456))
print(special_format(12345678901234567890))
print(special_format(1.0))
print(special_format(12.34))
print(special_format(1234567890.1234567890))
上面的示例将导致以下输出:
1
12
123
1,234
12,345
1,23,456
1,23,45,67,89,01,23,45,67,890
1.0
12.34
1,23,45,67,890.1234567
请参阅在 ideone.com 上运行的此代码