Java:BigDecimal和Double.NaN

Den*_*gin 6 java math numbers bigdecimal

我正在尝试执行以下代码:

import java.math.*;

public class HelloWorld{

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

合理地说,我得到:

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)    
Run Code Online (Sandbox Code Playgroud)

有没有办法在BigDecimal中表示Double.NaN

Ste*_*n C 8

有没有办法在BigDecimal中表示Double.NaN?

不.BigDecimal该类不提供NaN,+∞或-∞的表示.

您可以考虑使用null...除了您需要至少3个不同的null值来表示3种可能的情况,这是不可能的.

您可以考虑创建一个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
}
Run Code Online (Sandbox Code Playgroud)


Amr*_*Amr 2

NaN = 不是数字。它不是数字,因此无法转换为 BigDecimal

  • BigDecimal 是一个对象。也许您只将其设置为 null? (4认同)
  • “合理的建议”......直到您考虑 Double.NEGATIVE_INFINITY 和 Double.POSITIVE_INFINITY (3认同)