7

BigDecimal任意の値を含むJava を正規の形式に縮小して、メソッドBigDecimalを使用して同じ数を表す 2 つの値が等しくなるようにする最も簡単な方法は何equals()ですか?

次のようなコードを使用して、任意の文字列から数値を解析しています。

BigDecimal x = new BigDecimal(string1, MathContext.DECIMAL64);
BigDecimal y = new BigDecimal(string2, MathContext.DECIMAL64);

( string1, string2) は任意であるため、たとえば ( "1", "1.0000") または ( "-32.5", "1981")...のようになります。

私が探しているのは、上記のアサーションが正規化するメソッドの最も単純な (最短/クリーンなコード) 実装です。

assert x.compareTo(y) != 0 ||
    (canonicalize(x).equals(canonicalize(y)) && 
     x.compareTo(canonicalize(x)) == 0 && y.compareTo(canonicalize(y)) == 0);

成功します...:

public static BigDecimal canonicalize(BigDecimal b) {
    // TODO:
}
4

2 に答える 2

3

If you want to know if two BigDecimals are equal regardless of scale, just use .compareTo()

public static boolean bigDecimalEquals(BigDecimal b1, BigDecimal b2) {
    return b1.compareTo(b1) == 0;
}

It specifically recommends this in the Javadoc

Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=).


If you actually want to convert the BigDecimal so that .equals() will work, just use the setScale method.

于 2014-10-13T21:47:45.933 に答える