You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.8如何实现浮点数整数与小数部分的下划线分组格式化?

Python 3.8 实现浮点数整数+小数部分下划线分组格式化

Python 3.8 原生仅支持整数部分的千位下划线分组,小数部分的分组确实没有内置方法,不过可以自己写个函数实现需求,核心思路是拆分整数和小数部分分别处理后再拼接:

实现代码

import re

def format_float_with_underscores(num):
    # 把数字转为字符串,处理科学计数法并去除末尾多余的0和点
    num_str = f"{num:.10f}".rstrip('0').rstrip('.') if '.' in f"{num:.10f}" else str(num)
    
    # 拆分整数与小数部分
    if '.' in num_str:
        int_part, dec_part = num_str.split('.', 1)
    else:
        int_part, dec_part = num_str, ''
    
    # 处理整数部分:用千位逗号分隔后替换成下划线
    formatted_int = f"{int(int_part):,}".replace(',', '_') if int_part else '0'
    
    # 处理小数部分:每三位插入一个下划线
    formatted_dec = re.sub(r'(.{3})(?!$)', r'\1_', dec_part) if dec_part else ''
    
    # 拼接结果
    return f"{formatted_int}.{formatted_dec}" if formatted_dec else formatted_int

测试示例

print(format_float_with_underscores(4321.000056))  # 输出: 4_321.000_056
print(format_float_with_underscores(1234567.890123))  # 输出: 1_234_567.890_123
print(format_float_with_underscores(0.123456))  # 输出: 0.123_456
print(format_float_with_underscores(123.45))  # 输出: 123.45
print(format_float_with_underscores(1000000))  # 输出: 1_000_000

说明

  • 函数处理了科学计数法的情况,确保数字转为常规十进制字符串;
  • 整数部分利用Python原生的千位逗号格式化,再替换成下划线,简单高效;
  • 小数部分用正则表达式实现每三位插入下划线,同时避免在末尾添加多余的下划线;
  • 兼容纯整数、短小数、多位数整数等多种场景。

内容的提问来源于stack exchange,提问作者Jason

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 14:23:10