Java: BigDecimal and Double.NaN

I am trying to execute the following code:

import java.math.*;

public class HelloWorld{

     public static void main(String []args){
            System.out.println(BigDecimal.valueOf(Double.NaN));
     }
}

And reasonably, I get:

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 any way to introduce Double.NaN in BigDecimal?

+4
source share
5 answers

Is there any way to introduce Double.NaN in BigDecimal?

No. The class BigDecimaldoes not provide a representation for NaN, + ∞ or -∞.

You can use null... except that you need at least 3 different values nullto represent the three possible cases, and that is not possible.

BigDecimal, "" , "" BigDecimal NaN .. ; .

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
}
+7

"NaN" " ". "" , , undefined. , 0.0, 0.0, undefined. undefined.

BigDecimal.valueOf(Double.NaN)It tries to convert Double.NaNto BigDecimal, and the result - the number cannot be converted to BigDecimalie java.lang.NumberFormatException.

+3
source

NaN = not a number. Its not a number, so it cannot be converted to BigDecimal

+2
source

You can rewrite your code as follows:

 public static void main(String []args){
     Double d = ...;
     String value; 

     if (Double.isNaN(d) ==  true) {
         value= "My-NaN-formatting";
     } else {
         value=BigDecimal.valueOf(d);
     }

     System.out.println(value);
 }
+1
source

All Articles