Interestingly, the values ββseem to be equal, and subtraction gives you a null value, it seems to be a problem with the print code. The following code:
import java.math.BigDecimal; public class Test { public static void main(String args[]) { BigDecimal b1 = new BigDecimal(0.01); BigDecimal b2 = new BigDecimal(0.01); BigDecimal b3 = new BigDecimal(0); if (b1.compareTo(b2) == 0) System.out.println("equal 1"); b1 = b1.subtract(b2); if (b1.compareTo(b3) == 0) System.out.println("equal 2"); System.out.println("BigDecimal result: "+ b1); } }
displays both equal messages, indicating that the values match, and when subtracting you get zero .
You can try to raise this as an error and see what Oracle returns with. They'll probably just indicate that 0e-59 is still zero, so itβs not an error, or that the rather complicated behavior described on the documentation page of BigDecimal works as intended. In particular, the point that reads:
There is a one-to-one mapping between the distinguishable values ββof BigDecimal and the result of this conversion. That is, each distinguishable BigDecimal value (unscaled value and scale) has a unique string representation as a result of using toString. If this string representation is converted back to BigDecimal using the BigDecimal (String) constructor, then the original value will be restored.
The fact that the original value needs to be restored means that toString() needs to create a unique row for each scale, so you get 0e-59 . Otherwise, converting the string back to BigDecimal may give you a different value (unscaled-value / scale tuple).
If you really want the zero to display as β0β regardless of scale, you can use something like:
if (b1.compareTo(BigDecimal.ZERO) == 0) b1 = new BigDecimal(0);
paxdiablo
source share