Sunday, 15 January 2012

java - Canonical representation of a BigDecimal -



java - Canonical representation of a BigDecimal -

what simplest way cut down java bigdecimal containing arbitrary value canonical form 2 bigdecimal's representing same number compare equal using equals() method?

i parsing numbers arbitrary strings using code this:

bigdecimal x = new bigdecimal(string1, mathcontext.decimal64); bigdecimal y = new bigdecimal(string2, mathcontext.decimal64);

since (string1, string2) arbitrary, be, e.g., ("1", "1.0000") or ("-32.5", "1981")...

what i'm looking simplest (shortest/cleanest code) implementation of method canonicalize above assertion

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) { // todo: }

if want know if 2 bigdecimals equal regardless of scale, utilize .compareto()

public static boolean bigdecimalequals(bigdecimal b1, bigdecimal b2) { homecoming b1.compareto(b1) == 0; }

it recommends in javadoc

two bigdecimal objects equal in value have different scale (like 2.0 , 2.00) considered equal method. method provided in preference individual methods each of 6 boolean comparing operators (<, ==, >, >=, !=, <=).

if want convert bigdecimal .equals() work, utilize setscale method.

java math equals bigdecimal canonicalization

No comments:

Post a Comment