Java:BigDecimal和Double.NaN [英] Java: BigDecimal and Double.NaN

查看:235
本文介绍了Java:BigDecimal和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));
     }
}

合理地说,我得到了:

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)    

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

Is there a way to represent Double.NaN in BigDecimal?

推荐答案

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

Is there a way to represent Double.NaN in BigDecimal?

不. BigDecimal类不表示NaN,+∞或-∞.

No. The BigDecimal class provides no representation for NaN, +∞ or -∞.

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

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.

您可以考虑创建处理这些特殊"值的BigDecimal的子类,但是将数字"实现为BigDecimal的包装可能更简单,并且将NaN等视为特殊对象案件;例如

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
}

这篇关于Java:BigDecimal和Double.NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆