# Double equality

Janis Strautins
Greenhorn
Posts: 20
Hi.
I have to do a double comparison, I have tried many things, but nothing really works.. they are responsible for stopping a cycle.
First off, compared double's them selves using (double) Math.round(x*10000000)/10000000, worked fine but then.. Numbers were the same, but weren't(and vice versa), so the cycle continued endlessly.
Tried rounding them and comparing long values, still the same.
Lastly, tried using Big-decimal, ran into problems yet again.

Whats wrong with this code? As far as i know, it's best to use the string constructor, so I'm using it. The second line returns a juicy "java.lang.NumberFormatException", if I edit the 2nd line to, for example, 5.3222, after a while, the first line returns the same error. Should I replace doubles with BigDecimals, only for this comparison? That seems silly to me, there has to be an easy way to do this comparison.

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15559
46
Janis Strautins wrote:As far as i know, it's best to use the string constructor, so I'm using it.

You should understand why people say it's best to use the constructor that takes a string, then you'd realise that if you already have a double, it makes no sense to first convert it to a string so that you can use BigDecimal's constructor that takes a string.

The reason why someone told you that it's best to use the constructor that takes a string, is because double is inherently imprecise, and it can't accurately store values such as for example 0.1. For example, if you do this:

you get:
0.1000000000000000055511151231257827021181583404541015625

If you specify the number in the form of a string "0.1", you won't suffer from the fact that double can't store it precisely:

I don't know what your code looks like, but precise comparisons of double values, using ==, often return false, because there are small rounding errors. Don't use == to compare double values; instead of that, check if they are close enough to each other. For example: