Search code examples
javadoublebigdecimal

Compare that BigDecimal value and double value are equal to two decimal places


I'm working with an API that returns a double value. I need to compare that value to a BigDecimal value for equality to two decimal places.

Should I convert BigDecimal to double and then compare

Math.abs(myBigDecimal.doubleValue() - apiDouble) >= .01

Or are there issues with this approach? Perhaps I should convert the double into a BigDecimal and and then compare?


Solution

  • No. Although IEEE double has guard bits, it cannot exactly represent a decimal value. Convert the double to a BigDecimal, using rounding, and then use compareTo(). Note that equals() takes into account decimal positions, so compareTo() is safer. You may need to round the BigDecimal as well.