如何比较Java中的两个double值? [英] How to compare two double values in Java?

查看:259
本文介绍了如何比较Java中的两个double值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中两个double值的简单比较会产生一些问题。让我们考虑Java中的以下简单代码片段。

A simple comparison of two double values in Java creates some problems. Let's consider the following simple code snippet in Java.

package doublecomparision;

final public class DoubleComparision 
{
    public static void main(String[] args) 
    {
        double a = 1.000001;
        double b = 0.000001;

        System.out.println("\n"+((a-b)==1.0));
    }
}






上面的代码似乎返回 true ,表达式的评估((ab)== 1.0)但它没有T。它返回 false ,因为此表达式的评估是 0.9999999999999999 实际上预计 1.0 不等于 1.0 因此,条件的计算结果为布尔 false 。克服这种情况的最佳和建议方法是什么?


The above code appears to return true, the evaluation of the expression ((a-b)==1.0) but it doesn't. It returns false instead because the evaluation of this expression is 0.9999999999999999 which was actually expected to be 1.0 which is not equal to 1.0 hence, the condition evaluates to boolean false. What is the best and suggested way to overcome such a situation?

推荐答案

基本上你不应该进行精确的比较,你应该做什么这样的事情:

Basically you shouldn't do exact comparisons, you should do something like this:

double a = 1.000001;
double b = 0.000001;
double c = a-b;
if (Math.abs(c-1.0) <= 0.000001) {...}

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

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