【问题标题】:How to compare a Python float with a Mysql decimal in python?如何在 python 中比较 Python 浮点数和 Mysql 小数?
【发布时间】:2016-05-06 02:39:14
【问题描述】:

我在 mysql 中将价格存储为小数(8,2),我需要将相等性与 python 中的浮点数进行比较。

假设我在数据库中有4.28select 返回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

谢谢

【问题讨论】:

  • price[0] 已经是十进制。你为什么要像decimal.Decimal(price[0])一样再次将其转换为十进制?因为decimal.Decimal(decimal.Decimal(4.28)) 在我的笔记本电脑中返回了Decimal('4.28000000000000024868995751603506505489349365234375')
  • @ozgur price[0] 是从数据库返回的值(使用 mysqldb),它不是 Python 十进制,字面意思是 Decimal(4.28)

标签: python mysql compare decimal


【解决方案1】:

不,没有其他方法可以比较数字的浮点表示是否相等,但有一些方法可以使其实用:

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

【讨论】:

  • abs() 部分的好选择。我只会使用一次,所以可能不需要为此制定方法。
【解决方案2】:

您需要将您要比较的内容转换为小数:

decimal.Decimal('4.28') == decimal.Decimal(price[0])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 2012-05-13
    • 2016-05-24
    相关资源
    最近更新 更多