Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check Equal and Not Equal conditons for double values

I am facing difficulty in comparing two double values using == and !=.

I have created 6 double variables and trying to compare in If condition.

double a,b,c,d,e,f;

if((a==b||c==d||e==f))
{
//My code here in case of true condition
}
else if ((a!=b||c!=d||e!=f))
{
//My code here in case false condition
}

Though my condition is a and b are equal control is going to else if part

So I have tried a.equals(b) for equal condition, Which is working fine for me.

My query here is how can I check a not equal b. I have searched the web but I found only to use != but somehow this is not working for me.

like image 413
Siva Avatar asked Jul 23 '14 05:07

Siva


People also ask

Can you use == for doubles?

Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result. For this reason, we must use a more complex comparison algorithm.

How do you know if a double equals?

equals() is a built-in function in java that compares this object to the specified object. The result is true if and only if the argument is not null and is a Double object that contains the same double value as this object. It returns false if both the objects are not same.

How do you say not equal in Javascript?

The inequality operator ( != ) checks whether its two operands are not equal, returning a Boolean result.


1 Answers

If you're using a double (the primitive type) then a and b must not be equal.

double a = 1.0;
double b = 1.0;
System.out.println(a == b);

If .equals() works you're probably using the object wrapper type Double. Also, the equivalent of != with .equals() is

!a.equals(b)

Edit

Also,

else if ((a!=b||c!=d||e!=f))
{
  //My code here in case false condition
}

(Unless I'm missing something) should just be

else 
{
  //My code here in case false condition
}

if you really want invert your test conditions and test again,

 else if (!(a==b||c==d||e==f))

Or use De Morgan's Laws

 else if (a != b && c != d && e != f)
like image 58
Elliott Frisch Avatar answered Oct 15 '22 07:10

Elliott Frisch