Search code examples
javabigdecimal

BigDecimal in Java


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));

Solution

  • 0.02 gets evaluated to

    java.math.BigDecimal = 0.0200000000000000004163336342344337026588618755340576171875
    

    You have to setScale(2, RoundingMode.HALF_EVEN) there too.