Python中如何精确控制小数精度并避免浮点数问题
a = 0.9987623
# 将 a 保留两位小数得到
a = 0.99
Python中如何精确控制小数精度并避免浮点数问题
round()
在Python里处理小数精度,直接用float肯定不行,那玩意儿是二进制浮点数,算钱或者需要精确结果的时候容易出问题。给你两个最常用的方案:
方案一:用 decimal 模块
这是处理十进制运算的标准库,特别适合金融计算。
from decimal import Decimal, getcontext
# 设置全局精度(小数点后位数)
getcontext().prec = 6 # 设置6位有效数字
a = Decimal('0.1')
b = Decimal('0.2')
c = a + b
print(c) # 输出: 0.3
# 更精确的例子
getcontext().prec = 28 # Decimal默认28位
result = Decimal('1') / Decimal('7')
print(result) # 输出: 0.1428571428571428571428571429
注意:创建Decimal对象时一定要用字符串,如果用Decimal(0.1),传入的已经是浮点数误差了。
方案二:直接四舍五入输出 如果只是显示时需要控制位数,用格式化就行:
x = 0.1 + 0.2
print(f"{x:.2f}") # 输出: 0.30
print(round(x, 4)) # 输出: 0.3
不过这只是显示效果,内存里的值还是浮点数。
简单总结:要精确计算就用decimal,只是显示控制就用格式化。
format
In [2]: a = 0.998765
In [3]: round(a,2)
Out[3]: 1.0
>>> r = lambda f: f - f % 0.01
>>> r(2.368)
2.36
>>> r(2.36888888)
2.36
>>> r(2.323)
2.32
>>> r(2.326)
2.32
摘自: https://www.reddit.com/r/learnpython/comments/4nj5gu/how_to_get_float_to_two_decimal_places_without/
int(a*100)/100
Q. In a fixed-point application with two decimal places, some inputs have many places and need to be rounded. Others are not supposed to have excess digits and need to be validated. What methods should be used?
A. The quantize() method rounds to a fixed number of decimal places. If the Inexact trap is set, it is also useful for validation:
>>>
>>> TWOPLACES = Decimal(10) ** -2 # same as Decimal(‘0.01’)
>>>
>>> # Round to two places
>>> Decimal(‘3.214’).quantize(TWOPLACES)
Decimal(‘3.21’)
这就厉害了


