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.<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)
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With