Reputation: 4645
I am thinking of using BigDecimal to compare two currency values rounded to 2 digits. For example I expect the following to yield 0 because I'm comparing something that should round to 0.02 with something that is 0.02. But it yields -1 !! Is there a right way to do this?
This should also work for larger numbers like 123.45 vs 123.4534 ... which should yield 0 when "compareTo" is used.
I've tried using math context but it doesnt seem elegant ... is there a correct way?
BigDecimal spread = new BigDecimal(0.01934);
spread.setScale(2, RoundingMode.HALF_EVEN);
System.out.format("0.0193 ? 0.02 = %d\n", spread.compareTo(new BigDecimal(0.02)));
AND THE SOLUTION IS:
BigDecimal spread = new BigDecimal(0.01934).setScale(2, RoundingMode.HALF_EVEN);
BigDecimal loSpread = new BigDecimal(0.02).setScale(2, RoundingMode.HALF_EVEN);
System.out.format("0.0193 ? 0.02 = %d\n", spread.compareTo(loSpread));
Upvotes: 7
Views: 855
Reputation: 285430
First off, BigDecimal is immutable. You must return the result from your setScale method call:
spread = spread.setScale(2, RoundingMode.HALF_EVEN);
Next you must improve your accuracy of the second BigDecimal since it is being derived from a double -- not a very accurate entity. So try a String:
spread.compareTo(new BigDecimal("0.02"))
Upvotes: 10
Reputation: 36269
0.02 gets evaluated to
java.math.BigDecimal = 0.0200000000000000004163336342344337026588618755340576171875
You have to setScale(2, RoundingMode.HALF_EVEN) there too.
Upvotes: 5