经过一番折腾后,我想出了以下代码,将任何 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;
}
最佳答案
我不知道有什么方法可以用更少的代码编写它,就像在某些可以简化部分代码的方法中一样。但是,我可能会重载 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);
}
关于java - 任何数字类型转换为 BigDecimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18542739/