在Python中,可以使用locale
模块来按照文化代码格式化数字。下面是一个示例代码:
import locale
# 设置文化代码
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # 使用英文格式化数字
# 格式化数字
number = 1234567.89
formatted_number = locale.format('%0.2f', number, grouping=True)
print(formatted_number) # 1,234,567.89
在上述代码中,首先导入了locale
模块。然后使用setlocale()
函数将文化代码设置为en_US.UTF-8
,这表示使用英文格式化数字。
接下来,定义了一个数字number
,然后使用format()
函数对其进行格式化。'%0.2f'
表示将数字格式化为带有两位小数的浮点数。grouping=True
表示在数字中添加千位分隔符。
最后,使用print()
函数打印出格式化后的数字formatted_number
,输出结果为1,234,567.89
。
下一篇:按照文件编号在特定文件夹中排序