← 中文资源

简体中文版本

locale 交给你做货币格式化

locale.currency 与 format_string 按 localeconv 里的符号和分组规则渲染金额:千分位与小数约定来自区域数据库,不要手写字符串拼接。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

currency : ¥1,234,567.89
number   : 1,234,567.89
symbol   : ¥ | grouping: [3, 0]

实现说明

amount、conv 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 每一步打印都带着自己的标签:currency :。

常见问题

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。 全部导入都来自标准库:locale。 文件的状态由几个模块级绑定持有:amount、conv。

代码示例

import locale

# locale.setlocale 不带 category 参数时只设 LC_CTYPE:
# 货币/数字格式化必须显式传 LC_MONETARY / LC_ALL
locale.setlocale(locale.LC_ALL, "")

amount = 1234567.891
print("currency :", locale.currency(amount, grouping=True))
print("number   :", locale.format_string("%.2f", amount, grouping=True))

# localeconv 暴露当前区域的符号与分组规则,调试格式差异用
conv = locale.localeconv()
print("symbol   :", conv["currency_symbol"], "| grouping:", conv["mon_grouping"])