java.lang.NumberFormatException: Infinite or NaN緣由之浮點類型除數爲0結果探究

背景

在對Double類型的數據進行計算操做,將結果轉化爲BigDecimal時拋出了下面的異常,進行了Debug才發現了問題緣由,同時也暴露出了本身在一些基礎知識上還有些欠缺。java

Exception in thread "main" java.lang.NumberFormatException: Infinite or NaN
	at java.math.BigDecimal.<init>(BigDecimal.java:895)
	at java.math.BigDecimal.<init>(BigDecimal.java:872)
	at com.lingyejun.authenticator.DoubleTest.main(DoubleTest.java:13)
複製代碼

概念補充

在java中進行數字類型運算的時,以前一直有一種錯誤的觀念,即進行除法運算時當除數爲0時在運行時會拋出java.lang.ArithmeticException: / by zero運行時異常。如此想固然的覺得對於浮點類型如Float和Double也是如此,下面一段代碼即可以說明問題。ui

package com.lingyejun.authenticator;

public class DoubleTest {

    public static void main(String[] args) {
        Double d1 = 10 / 0D;
        Double d2 = -10 / 0D;
        Double d3 = 0.0 / 0D;
        System.out.println("d1=" + d1 + " d2=" + d2 + " d3=" + d3);
    }
}
複製代碼

運算結果爲「d1=Infinity d2=-Infinity d3=NaN」,什麼?數字運算竟然還能算出來了字符串???打印出來的Infinity、-Infinit、NaN其實不是字符串,而是double類型的常量,查看源碼註釋便懂了。spa

/**
 * A constant holding the positive infinity of type
 * {@code double}. It is equal to the value returned by
 * {@code Double.longBitsToDouble(0x7ff0000000000000L)}.
 */
public static final double POSITIVE_INFINITY = 1.0 / 0.0;

/**
 * A constant holding the negative infinity of type
 * {@code double}. It is equal to the value returned by
 * {@code Double.longBitsToDouble(0xfff0000000000000L)}.
 */
public static final double NEGATIVE_INFINITY = -1.0 / 0.0;

/**
 * A constant holding a Not-a-Number (NaN) value of type
 * {@code double}. It is equivalent to the value returned by
 * {@code Double.longBitsToDouble(0x7ff8000000000000L)}.
 */
public static final double NaN = 0.0d / 0.0;
複製代碼

正無窮:POSITIVE_INFINITY,正數除以零獲得正無窮。code

負無窮:NEGATIVE_INFINITY,負數除以零獲得負無窮。orm

非數字:NaN,0除以0時獲得非數字。 對象

異常緣由  

經過查看BigDecimal類中針對Double類型數據的構造方法,咱們知道了,在構造BigDecimal對象時,構造方法中傳入的Double類型爲無窮大或非數字時會拋出NumberFormatException異常。ci

public BigDecimal(double val, MathContext mc) {
        if (Double.isInfinite(val) || Double.isNaN(val))
            throw new NumberFormatException("Infinite or NaN");
複製代碼

撥雲見日探究清楚以後,一切都是那樣的理所應當。字符串

相關文章
相關標籤/搜索