According to the JavaDoc for BigDecimal, the compareTo function does not account for the scale during comparison.
Now I have a test case that looks something like this:
BigDecimal result = callSomeService(foo);
assertTrue(result.compareTo(new BigDecimal(0.7)) == 0); //this does not work
assertTrue(result.equals(new BigDecimal(0.7).setScale(10, BigDecimal.ROUND_HALF_UP))); //this works
The value I’m expecting the function to return is 0.7 and has a scale of 10. Printing the value shows me the expected result. But the compareTo() function doesn’t seem to be working the way I think it should.
What’s going on here?
new BigDecimal(0.7)does not represent 0.7.It represents 0.6999999999999999555910790149937383830547332763671875 (exactly).
The reason for this is that the
doubleliteral0.7doesn’t represent 0.7 exactly.If you need precise
BigDecimalvalues, you must use theStringconstructor (actually all constructors that don’t takedoublevalues will work).Try
new BigDecimal("0.7")instead.The JavaDoc of the
BigDecimal(double)constructor has some related notes:So to summarize: If you want to create a
BigDecimalwith a fixed decimal value, use theStringconstructor. If you already have adoublevalue, thenBigDecimal.valueOf(double)will provide a more intuitive behaviour than usingnew BigDecimal(double).