BigDecimal的任何数字类型

时间:2013-08-30 23:12:21

标签: java bigdecimal

经过大量的搞乱后,我想出了以下代码,将任何Number子类转换为BigDecimal。

但我不相信这段代码是完全正确的。我当然不高兴它是多么的冗长!

有没有更好的方法来做到这一点,并且我需要注意这种方法的任何缺陷(除了我已经知道的浮点不精确表示问题)?

public DecimalSpec setValue (Number value) {
    if (value instanceof Double) {
        if ((((Double) value).isNaN ())
        || (((Double) value).isInfinite ())) {
            throw new IllegalArgumentException ("Infinite or NaN values not allowed");
        }
    }
    this.value  = new BigDecimal (value.toString ());
    return this;
}

2 个答案:

答案 0 :(得分:2)

我不知道有什么方法可以用更少的代码来编写代码,就像在一些方法中那样会缩短部分代码。但是,我可能会重载Double的方法,或让BigDecimal改为NumberFormatException

BigDecimal完成工作:

/** May throw NumberFormatException or NullPointerException. */
public DecimalSpec setValue (Number value) {
    this.value  = new BigDecimal (value.toString ());
    return this;
}

Double的重载:

/** May throw NullPointerException. */
public DecimalSpec setValue (Number value) {
    this.value  = new BigDecimal (value.toString ());
    return this;
}

/** May throw NullPointerException or IllegalArgumentException. */
public DecimalSpec setValue (Double value) {
    if (value.isNaN () || value.isInfinite ()) {
        throw new IllegalArgumentException ("Infinite or NaN values not allowed");
    }
    return this.setValue ((Number) value);
}

答案 1 :(得分:1)

我认为你有设计问题。让setValue开始BigDecimal。然后,将其他类型转换为BigDecimal的代码可以在代码中的其他位置。您可以自由地为各种类型重置BigDecimal转换,并且可以根据输入类型转换为BigDecimal

如,

public class BigDecimalConverter {
    public static toBigDecimal(int i) { ... }
    public static toBigDecimal(double i) { ... }
    ...
}

然后

public DecimalSpec setValue (BigDecimal value) {
    this.value  = value;
    return this;
}

decimalSpec.setValue(BigDecimalConverter.toBigDecimal(myNumber));

当然不完美,但这是一般的想法。一段代码永远不应该做太多的工作。如果在某些时候需要接受未知类型的转换,您可以考虑使用转换器interface,然后考虑工厂类(可能不是正确的模式名称)来为您提供正确的类型。