Java: BigDecimal and Double.NaN

做~自己de王妃 提交于 2020-01-14 08:05:13

问题


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?


回答1:


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
}



回答2:


"NaN" stands for "not a number". "Nan" is produced if a floating point operation has some input parameters that cause the operation to produce some undefined result. For example, 0.0 divided by 0.0 is arithmetically undefined. Taking the square root of a negative number is also undefined.

BigDecimal.valueOf(Double.NaN) It trying to convert Double.NaN to BigDecimal, and result is number can not be converted in to BigDecimal i.e. java.lang.NumberFormatException.




回答3:


According to the docs it is not possible, see http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#BigDecimal%28double%29




回答4:


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




回答5:


You can rewrite your code like this:

 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);
 }


来源:https://stackoverflow.com/questions/28065158/java-bigdecimal-and-double-nan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!