News for hackers. Stuff that matters.
Re:The Pitfalls of Comparing BigDecimals in Java by bsder on Monday June 17, 2024 @07:04PM (#40712202)
"0.0 + 0.05" and "0.00 + 0.05" are not the same so "0.0" and "0.00" should probably not be considered to be the same.
Re:The Pitfalls of Comparing BigDecimals in Java by happytoexplain on Monday June 17, 2024 @07:11PM (#40712255)
What are the results of those two examples?
Re:The Pitfalls of Comparing BigDecimals in Java by wging on Monday June 17, 2024 @07:40PM (#40712508)
Maybe GP was thinking of the optional rounding modes? With plain old add(), you get a BigDecimal 0.05 with scale 2 in both cases and the two examples are equal according to the equals() method.

    var a = new BigDecimal("0.0");
    var b = new BigDecimal("0.05");
    var result1 = a.add(b);

    var c = new BigDecimal("0.00");
    var result2 = c.add(b);
    System.out.println(result1); // 0.05
    System.out.println(result2); // 0.05
    System.out.println(result1.equals(result2)); // true
    System.out.println(result1.scale()); // 2
    System.out.println(result2.scale()); // 2
Re:The Pitfalls of Comparing BigDecimals in Java by bsder on Monday June 17, 2024 @08:30PM (#40712812)
Yeah, my bad, I was thinking about rounding.

I'm surprised that a.add(b) promotes to an extra decimal place.

That's a touch ... odd.

Re:The Pitfalls of Comparing BigDecimals in Java by wging on Monday June 17, 2024 @11:23PM (#40713788)
You could also think of it as declining to _lose_ a decimal place; a.add(b) ought to be the same as b.add(a), so there's no reason to prefer a's precision to b. You need to take the higher precision of the two for an exact result; I assume that's the rationale.

> The BigDecimal class gives its user complete control over rounding behavior. If no rounding mode is specified and the exact result cannot be represented, an exception is thrown ...

- https://docs.oracle.com/javase/8/docs/api/java/math/BigDecim...

Re:The Pitfalls of Comparing BigDecimals in Java by wging on Tuesday June 18, 2024 @12:57AM (#40714196)
https://docs.oracle.com/en/java/javase/21/docs/api/java.base... is probably a better link (though it's not that different)
Re:The Pitfalls of Comparing BigDecimals in Java by bsder on Tuesday June 18, 2024 @01:03AM (#40714211)
Thanks for the link.

Apparently, restricted behavior like I expected is reserved for if you use a MathContext.

> Instead, for the BigDecimal operations taking a MathContext parameter, if the MathContext has a nonzero precision, the set of possible representable values for the result is determined by the precision of the MathContext argument.

Very strange. I would have expected something that is going to be mostly used for currency to not do implicit things by default.