我在 mysql 中将价格存储为 decimal(8,2),我需要在 python 中比较相等性和 float 。
假设我有 4.28
在数据库和select
返回 price = (Decimal(4.28),)
.我通过 decimal.Decimal(price[0])
将它转换为 python 十进制,但是 decimal.Decimal(price[0]) == 4.28
返回 false。
有没有一种方法可以直接比较相等性,而不是将差异与一个小数字进行比较,即
decimal.Decimal(price[0]) - decimal.Decimal(4.28) < 0.01
谢谢
最佳答案
不,没有其他方法可以比较数字的浮点表示是否相等,但有一些方法可以使其实用:
decimal.Decimal(price[0]) - decimal.Decimal(4.28) < 0.01
应该是:
abs(decimal.Decimal(price[0]) - decimal.Decimal(4.28)) < 0.01
你可以抽象比较:
def almost_equal(a, b, epsilon=1e-5):
"""returns true is the absolute value of the difference between a & b
is less than epsilon i/e a & b are almost equal, False otherwise
"""
return abs(a - b) < epsilon
关于python - 如何在 Python 中比较 Python float 和 Mysql 小数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37063346/