For Double/Float, there are some rounding errors and loss of precision when converting from decimal to binary representation. For example, setting float to "6.1" and then printing it out again, you may get a reported value of something like "6.099999904632568359375". Which is the better option for checking equality of 2 Double objects : Using BigDecimal or (Math.abs(double1 - double2) < epsilon)
-
2Depends on what you need: exact equality, or just approximate equality. This depends on your needs, there's no universal rule. – Louis Wasserman Feb 01 '17 at 07:06
-
Possible duplicate of [Performant way to check java.lang.Double for equality](http://stackoverflow.com/questions/17971226/performant-way-to-check-java-lang-double-for-equality) – Dth Feb 01 '17 at 07:08
6 Answers
It depends on your usecase. If you work with currency, go for BigDecimal.
Otherwise if you can live with approximations use Math.abs(double1 - double2) < epsilon

- 14,596
- 22
- 87
- 108
With Guava, you have:
DoubleMath.fuzzyEquals(double a, double b, double tolerance)
and
DoubleMath.fuzzyCompare(double a, double b, double tolerance)
They are easier to use and more correct than writing "Math.abs(a-b) <= EPSILON". They cover the cases of Double.NaN and the infinities.

- 3,079
- 3
- 25
- 57

- 51
- 2
- 4
Floating point numbers have what is called an epsilon tolerance, the minimum representable value. To compare floats check their difference is within tolerance.
Math.abs(a-b) <= EPSILON
Of course if you happen to be working with a number that is too big to fit in a double, you should use the big number variant. EPSILON is some tolerance several orders greater than Double.MIN_VALUE, but sufficiently small that the variance is negligible.

- 3,758
- 4
- 22
- 33
-
`Double.MIN_VALUE` is the smallest possible positive `double`, 2^(-1074). Your expression will return true only if `abs(a-b)` either equals that value, or is 0. `Double.MIN_VALUE` is not suitable for use as an epsilon. – ajb Feb 01 '17 at 07:21
-
Ummm, multiplying by 2 does not help. Anyway, if `a` and `b` are not equal and are around 1, their difference cannot be smaller than 2^(-53) because of how floating point numbers are represented. (And please don't respond by making the epsilon 2^(-53). It is still too small a tolerance.) – ajb Feb 01 '17 at 07:46
If you want to test equality you can use Double.compare()
or BigDecimal.
If you need want approximate equality then Math.abs(d1-d2) < epsilon

- 2,800
- 1
- 17
- 17
-
No need to use `Double.compare` to test equality. `==` works just as well. – ajb Feb 01 '17 at 07:14
It would be different based on the level of accuracy needed. But may be take a look at Java.lang.Double.equals() method.

- 439
- 4
- 5