经过一番折腾,我想出了以下代码,将任何 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;
}