Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: BigDecimal and Double.NaN

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?

like image 863
Denis Kulagin Avatar asked Jan 21 '15 10:01

Denis Kulagin


1 Answers

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
}
like image 155
Stephen C Avatar answered Sep 21 '22 08:09

Stephen C