如何比较Django中的浮点值 [英] How to compare float value in in Django

查看:171
本文介绍了如何比较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):
    ....

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

另请参见:

See also: What is the best way to compare floats for almost-equality in Python?

这篇关于如何比较Django中的浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆