Python如何实现浮点数小数位数可配置的打印?
动态配置小数位数的几种优雅实现
下面是几种无需提前截断数值,直接通过动态生成格式字符串来配置小数位数的方法:
方法1:用f-string动态生成旧式%格式化模板
先定义小数位数变量,拼接出对应的格式字符串后,再用%格式化填充数值:
import numpy as np decimal_places = 4 # 可随时修改此值调整小数位数 x, y, z, s = np.random.random(4) # 生成格式模板 format_template = f'[%0.{decimal_places}f,\t%0.{decimal_places}f,\t%0.{decimal_places}f,\t%0.{decimal_places}f]' str_out = format_template % (x, y, z, s) print(str_out)
如果需要格式化的数值数量较多,可用join简化模板生成:
single_format = f'%0.{decimal_places}f' format_template = '[' + ',\t'.join([single_format] * 4) + ']'
方法2:使用str.format()动态控制格式
定义小数位数变量后,构造带占位符的格式字符串,再用format填充数值:
import numpy as np decimal_places = 4 x, y, z, s = np.random.random(4) format_template = f'[{{0:0.{decimal_places}f}},\t{{1:0.{decimal_places}f}},\t{{2:0.{decimal_places}f}},\t{{3:0.{decimal_places}f}}]' str_out = format_template.format(x, y, z, s) print(str_out)
用join简化的版本:
single_format = f'{{:0.{decimal_places}f}}' format_template = '[' + ',\t'.join([single_format] * 4) + ']' str_out = format_template.format(x, y, z, s)
方法3:直接用f-string内嵌变量控制小数位数
这是最简洁的写法,直接在f-string的格式说明中引用小数位数变量:
import numpy as np decimal_places = 4 x, y, z, s = np.random.random(4) str_out = f'[{x:0.{decimal_places}f},\t{y:0.{decimal_places}f},\t{z:0.{decimal_places}f},\t{s:0.{decimal_places}f}]' print(str_out)
方法4:利用numpy自带的格式化工具
如果数值本身是numpy数组,可直接用np.array2string指定格式化规则:
import numpy as np decimal_places = 4 arr = np.random.random(4) str_out = np.array2string( arr, formatter={'float_kind': lambda x: f'{x:0.{decimal_places}f}'}, separator='\t' ) print(str_out)
内容的提问来源于stack exchange,提问作者horsemeat
相关产品推荐
相关产品推荐

