What is the easiest way to reduce Java BigDecimal containing an arbitrary value in canonical form, so that two BigDecimal representing the same number compare equal using equals() method?
I parse my numbers from arbitrary strings using the following code:
BigDecimal x = new BigDecimal(string1, MathContext.DECIMAL64); BigDecimal y = new BigDecimal(string2, MathContext.DECIMAL64);
Since ( string1 , string2 ) are arbitrary, they can be, for example, ( "1" , "1.0000" ) or ( "-32.5" , "1981" ) ...
I am looking for the simplest (shortest / cleanest code) implementation of the canonicalize method, for which the above statement
assert x.compareTo(y) != 0 || (canonicalize(x).equals(canonicalize(y)) && x.compareTo(canonicalize(x)) == 0 && y.compareTo(canonicalize(y)) == 0);
will succeed...:
public static BigDecimal canonicalize(BigDecimal b) {
source share