7

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

2 Answers 2

10

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"))
Sign up to request clarification or add additional context in comments.

3 Comments

This is actually used to compare prices. They may have to be instantiated from doubles.
@fodon: Then user unknown has part of your answer for you, and I have the other part (regarding BigDecimal being immutable).
I reverted the invalid edit. Folks, please comment or provide an additional answer if you aren't satisfied with an answer you see.
5

0.02 gets evaluated to

java.math.BigDecimal = 0.0200000000000000004163336342344337026588618755340576171875

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

2 Comments

That's another way to get an accurate floating point number. 1+.
Had to use both ideas here to get it right. Will post correct code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.