SQL中如何将多个数值列统一保留2位小数且无需重复调用round/format函数
全局设置浮点数统一保留2位小数的实现方案
以下是不同使用场景下的可行方法:
仅需统一输出显示的场景
如果不需要修改实际计算精度,只要求打印/展示时固定显示2位小数,可以用对应工具的全局配置:
Python原生环境
- 交互式运行环境默认输出修改:
修改sys.displayhook自定义交互输出规则:
import sys old_hook = sys.displayhook def two_decimal_hook(val): old_hook(round(val,2) if isinstance(val, float) else val) sys.displayhook = two_decimal_hook
配置后直接在交互终端输入浮点数,会自动展示保留2位小数的结果。
- 全局修改print输出规则:
重写内置print函数,自动处理浮点参数:
old_print = __builtins__.print def two_decimal_print(*args, **kwargs): processed = [round(arg,2) if isinstance(arg, float) else arg for arg in args] old_print(*processed, **kwargs) __builtins__.print = two_decimal_print
后续所有调用print()输出的浮点数都会自动保留2位。
数据工具场景
- NumPy全局打印配置:
import numpy as np np.set_printoptions(precision=2, floatmode='fixed')
- Pandas全局显示配置:
import pandas as pd pd.set_option('display.float_format', lambda x: f"{x:.2f}")
注意:以上配置仅修改显示效果,不会改变变量实际存储的浮点精度,计算过程依然使用原始精度。
需要计算过程统一精度的场景
如果要求运算过程中就固定保留2位精度,避免浮点累计误差,可以自定义浮点子类:
class Float2(float): def __repr__(self): return f"{round(self,2):.2f}" def __str__(self): return f"{round(self,2):.2f}" # 重载四则运算,返回结果自动转为Float2类型 def __add__(self, other): return Float2(super().__add__(other)) def __sub__(self, other): return Float2(super().__sub__(other)) def __mul__(self, other): return Float2(super().__mul__(other)) def __truediv__(self, other): return Float2(super().__truediv__(other)) # 其余运算方法可根据需求自行补充
使用时将需要处理的浮点数用Float2()包裹即可,后续所有运算、输出都会自动保留2位小数。
内容的提问来源于stack exchange,提问作者GuoLY96
相关产品推荐
相关产品推荐

