Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is good way to check equality between 2 doubles in Java

Tags:

java

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)

like image 208
kakoli Avatar asked Mar 11 '23 00:03

kakoli


2 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

like image 81
Burkhard Avatar answered Apr 30 '23 09:04

Burkhard


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.

like image 24
Constantin-Alexandru Tabacu Avatar answered Apr 30 '23 08:04

Constantin-Alexandru Tabacu