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));
}
}
And reasonably, I am getting:
Exception in thread "main" java.lang.NumberFormatException
at java.math.BigDecimal.(BigDecimal.java:470)
at java.math.BigDecimal.(BigDecimal.java:739)
at java.math.BigDecimal.valueOf(BigDecimal.java:1069)
at HelloWorld.main(HelloWorld.java:6)
Is there a way to represent Double.NaN in BigDecimal?
解决方案
Is there a way to represent Double.NaN in BigDecimal?
No. The BigDecimal class provides no representation for NaN, +∞ or -∞.
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.
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
}