如何在Python中固定浮点数的小数位数?附示例
Python 实现固定浮点数小数位数的方法
方法1:字符串格式化(直接得到固定小数位的显示形式)
如果需要得到显示为5位小数的结果(自动补全末尾零),用字符串格式化是最直接的方式,支持f-string或str.format()两种写法:
示例代码
li = [4.0, 5.15445454, 1.1] # f-string 写法(Python 3.6+ 支持) newli = [f"{num:.5f}" for num in li] print(newli) # 输出: ['4.00000', '5.15445', '1.10000'] # str.format() 写法 newli = ["{:.5f}".format(num) for num in li] print(newli) # 同样得到 ['4.00000', '5.15445', '1.10000']
如果需要转回浮点数:注意浮点数本身不会存储末尾的零(比如4.00000转成浮点数后是4.0),但显示时仍可通过格式化保持5位小数:
newli_float = [float(f"{num:.5f}") for num in li] print(newli_float) # 输出: [4.0, 5.15445, 1.1] # 格式化显示补零 for num in newli_float: print(f"{num:.5f}") # 依次输出 4.00000、5.15445、1.10000
方法2:round()函数 + 格式化
先对数值四舍五入到5位小数,再格式化补零显示:
li = [4.0, 5.15445454, 1.1] rounded_li = [round(num, 5) for num in li] # 格式化显示 for num in rounded_li: print(f"{num:.5f}")
round(num, 5)负责数值层面的四舍五入,格式化则补全末尾的零。
方法3:decimal模块(精确控制小数位,避免浮点数精度问题)
如果需要精确的小数运算(比如金融场景),用decimal模块可以精准控制小数位数和舍入规则:
from decimal import Decimal, ROUND_HALF_UP li = [4.0, 5.15445454, 1.1] # 转换为Decimal类型,保留5位小数(四舍五入) newli_decimal = [Decimal(str(num)).quantize(Decimal('0.00000'), rounding=ROUND_HALF_UP) for num in li] # 转为字符串或浮点数 newli_str = [str(num) for num in newli_decimal] newli_float = [float(num) for num in newli_decimal] print(newli_str) # 输出: ['4.00000', '5.15445', '1.10000']
内容的提问来源于stack exchange,提问作者Partho Debnath
相关产品推荐
相关产品推荐

