File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Double equality Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Double equality" Watch "Double equality" New topic

Double equality

Janis Strautins

Joined: Dec 12, 2012
Posts: 19
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.
Thanks in advance!
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15084

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:

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:

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: Double equality
jQuery in Action, 3rd edition