tags:

views:

306

answers:

3

Comparing those two values shall result in a "true":

53.9173333333333  53.9173

Thanks in advance!

+7  A: 

If you want a = 1.00001 and b = 0.99999 be identified as equal:

return Math.abs(a - b) < 1e-4;

Otherwise, if you want a = 1.00010 and b = 1.00019 be identified as equal, and both a and b are positive and not huge:

return Math.floor(a * 10000) == Math.floor(b * 10000);
// compare by == is fine here because both sides are integral values.
// double can represent integral values below 2**53 exactly.

Otherwise, use the truncate method as shown in http://stackoverflow.com/questions/1976809/are-there-any-functions-for-truncating-a-double-in-java:

BigDecimal aa = new BigDecimal(a);
BigDecimal bb = new BigDecimal(b);
aa = aa.setScale(4, BigDecimal.ROUND_DOWN);
bb = bb.setScale(4, BigDecimal.ROUND_DOWN);
return aa.equals(bb);
KennyTM
Love these kind of solutions, simple and brilliant!
monoceres
@monoceres: ...and *wrong*
Michael Borgwardt
-1. @Michael is right. This solution is flawed. I'd like your explanation as to why ` System.out.println(12512310271255125d == 12512310271255124d);` prints `true` if double can represent integral values exactly. It's an obviously incorrect statement given the magnitudes doubles can work with. Then there's the fact that you shouldn't be using `==` on reference types like `BigDecimal`, but that's an easy fix.
Mark Peters
@Mark: Oops fixed.
KennyTM
Cool downvote removed. They're good solutions for most cases.
Mark Peters
+2  A: 

Naively:

if(Math.abs(a-b) < 0.0001)

However, that's not going to work correctly for all values. It's actually impossible to get it to work as long as you're using double, because double is implemented as binary fractons and does not even have decimal places.

You'll have to convert your values to String or BigDecimal to make meaningful tests about their decimal places.

You may want to read the Floating-Point Guide to improve your understanding of how floating point values work.

Michael Borgwardt
A: 

Thanks. I did it this way:

double lon = 23.567889;
BigDecimal bdLon = new BigDecimal(lon);
bdLon = bdLon.setScale(4, BigDecimal.ROUND_HALF_UP);

System.out.println(bdLon.doubleValue());
tzippy
You don't have to make a new answer, just accept the correct answer.
Martijn Courteaux