Skip to main content
 首页 » 编程设计

python之在python中的点后将 float 舍入为2位数字

2025年05月04日12powertoolsteam

我正在使用这段代码:

f = 0.3223322 
float('%.2f' % (f)) 

是否有没有 2 次转换的更 pythonic、更简洁的方法? 使用 round文档中的以下注释令人沮丧

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

请您参考如下方法:

round(number[, ndigits]) :

>>> round(0.3223322, 2) 
0.32 

请注意,由于浮点不精确,您可能仍希望在生成输出时使用一定精度的字符串格式化。

根据您要实现的目标,使用 Decimal 类型可能是合适的:

>>> from decimal import Decimal 
>>> round(Decimal(0.3223322), 2) 
Decimal('0.32') 

它以(令人惊讶的!)十进制而不是二进制进行数学运算,因此不会遇到任何十进制舍入问题(除非您最初尝试从 float 创建它)。