问题描述
我正在尝试执行以下代码:
I am trying to execute following code:
import java.math.*;
public class HelloWorld{
public static void main(String []args){
System.out.println(BigDecimal.valueOf(Double.NaN));
}
}
合理地说,我得到了:
Exception in thread "main" java.lang.NumberFormatException
at java.math.BigDecimal.<init>(BigDecimal.java:470)
at java.math.BigDecimal.<init>(BigDecimal.java:739)
at java.math.BigDecimal.valueOf(BigDecimal.java:1069)
at HelloWorld.main(HelloWorld.java:6)
有没有办法在BigDecimal中表示 Double.NaN ?
Is there a way to represent Double.NaN in BigDecimal?
推荐答案
不. BigDecimal
类不表示NaN,+∞或-∞.
No. The BigDecimal
class provides no representation for NaN, +∞ or -∞.
您可能会考虑使用null
...,但是您至少需要3个不同的null
值来表示3种可能的情况,但这是不可能的.
You might consider using null
... except that you need at least 3 distinct null
values to represent the 3 possible cases, and that is not possible.
您可以考虑创建处理这些特殊"值的BigDecimal
的子类,但是将数字"实现为BigDecimal
的包装可能更简单,并且将NaN
等视为特殊对象案件;例如
You could consider creating a subclass of BigDecimal
that handles these "special" values, but it may be simpler to implement your "numbers" as a wrapper for BigDecimal
, and treat NaN
and the like as special cases; e.g.
public class MyNumber {
private BigDecimal value;
private boolean isNaN;
...
private MyNumber(BigDecimal value, boolean isNaN) {
this.value = value;
this.isNaN = isNan;
}
public MyNumber multiply(MyNumber other) {
if (this.isNaN || other.isNaN) {
return new MyNumber(null, true);
} else {
return new MyNumber(this.value.multiply(other.value), false);
}
}
// etcetera
}
这篇关于Java:BigDecimal和Double.NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!