如何比较Django中的浮点值 [英] How to compare float value in in Django
本文介绍了如何比较Django中的浮点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我需要比较我的项目中的浮动值我使用下面的代码
Hi i need to compare the float value in my project i am using the folowing code
if style_score.style_quiz_score ==float(17.40):
但它不工作,但是当我将值从17.40更改为17它工作正常,请告诉我如何比较浮点值
but it not works for this but when i change the value from 17.40 to 17 it works fine, please tell me how can i compare the float value
推荐答案
这是因为舍入错误。从不比较浮动与 ==
,始终使用此模板:
That's because of rounding errors. Never compare floats with ==
, always use this template:
def floats_are_the_same(a,b): return abs(a-b) < 1e-6
if floats_are_the_same(value, 17.4):
....
b $ b
ie请检查该值是否关闭到某个所需的值。这是因为浮点运算几乎总是有舍入误差:
i.e. check that the value is close to some desired value. This is because float arithmetic almost always has rounding errors:
>>> 17.1 + 0.3
17.400000000000002
这篇关于如何比较Django中的浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文