Django十进制精度损失

时间:2017-09-13 14:58:31

标签: python django precision

worth = Decimal(request.POST.get('worth'))
print(request.user.profile.cash) # -> prints 10000.000000000000000
print(worth) # -> prints 10000
Profile.objects.filter(user=request.user).update(cash=F('cash')-worth)
request.user.profile.refresh_from_db()
if request.user.profile.cash < 0:
     ###!!!!####
     print(request.user.profile.cash) # -> -1.819E-12

#model definition:
class Profile(models.Model):
    cash = models.DecimalField(default=10000, max_digits=30, decimal_places=15)

可以看出,玩家有10k现金,我减去10k,这导致负值,我该如何解决这个问题?我不允许现金为负数,正如您所期望的那样。我做错了什么?

我希望玩家可以用他的钱全押。

1 个答案:

答案 0 :(得分:1)

您可以通过从python中的现金减去价值来解决这个问题(即不使用数据库查询)。我非常确定您必须先将价值转换为Decimal值才能执行此操作。这可能起作用的原因是Django使用Decimal模块中的decimal值来对十进制字段值进行算术运算,这些值具有十进制数字的完美精度。在进行查询时,我不确定数据库正在做什么,但它必须涉及某种浮点数学。您看到的值基本上等于零(-0.000000000001819)但包含一些浮点错误。

相关问题