java.lang.NumberFormatException: Infinite or NaN原因之浮点类型除数为0结果探究

背景

在对Double类型的数据进行计算操作,将结果转化为BigDecimal时抛出了下面的异常,进行了Debug才发现了问题原因,同时也暴露出了自己在一些基础知识上还有些欠缺。

1
2
3
4
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也是如此,下面一段代码便可以说明问题。

1
2
3
4
5
6
7
8
9
10
11
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类型的常量,查看源码注释便懂了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * 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,正数除以零得到正无穷。

负无穷:NEGATIVE_INFINITY,负数除以零得到负无穷。

非数字:NaN,0除以0时得到非数字。 

异常原因  

通过查看BigDecimal类中针对Double类型数据的构造方法,我们知道了,在构造BigDecimal对象时,构造方法中传入的Double类型为无穷大或非数字时会抛出NumberFormatException异常。

 

1
2
3
public BigDecimal(double val, MathContext mc) {
        if (Double.isInfinite(val) || Double.isNaN(val))
            throw new NumberFormatException("Infinite or NaN");
1
拨云见日探究清楚之后,一切都是那样的理所应当。
posted @   翎野君  阅读(4506)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示