如何在Python中实现带点分隔的货币数值格式化显示?
解决方案
有几种实用方法可以实现带点分隔的数值格式化需求:
方法1:字符串手动分割处理
将数字转为字符串后反转,按每三位分组用点连接,最后再反转回来:
money = 3467898542 s = str(money) reversed_str = s[::-1] formatted = '.'.join([reversed_str[i:i+3] for i in range(0, len(reversed_str), 3)])[::-1] print(formatted) # 输出:3.467.898.542
方法2:利用locale模块
通过配置区域实现千位分隔,再将默认的逗号替换为点:
import locale # 设置支持千位分隔的区域(如'ru_RU.UTF-8'或'en_US.UTF-8',需确保环境存在对应区域) locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8') money = 3467898542 formatted = locale.format_string('%d', money, grouping=True).replace(',', '.') print(formatted) # 输出:3.467.898.542
方法3:使用字符串格式化n类型
依赖系统区域的千位分隔规则,替换逗号为点:
money = 3467898542 formatted = f"{money:n}".replace(',', '.') print(formatted) # 输出:3.467.898.542
内容的提问来源于stack exchange,提问作者Kirill
相关产品推荐
相关产品推荐

