Java BigDecimal 可能的溢出错误
Java BigDecimal Possible Overflow Bug
我正在测试一些涉及 BigDecimal
的代码的边界条件,我注意到当使用字符串 "1e2147483647"
初始化 BigDecimal
时,它的行为异常。它的值似乎介于 0
和 1e-2147483647
之间。当我尝试调用 intValue()
时,我得到一个 NegativeArraySizeException
。我应该注意到 2147483647
是我系统上整数的最大值。我是不是做错了什么,或者这是 BigDecimal
的问题?
BigDecimal test = new BigDecimal("1e2147483647");
test.compareTo(new BigDecimal(0)); //Returns 1
test.compareTo(new BigDecimal("1e-2147483647")); //Returns -1
test.intValue(); //Throws NegativeArraySizeException
不,您似乎有一个合法的错误。该错误出现在 JDK7 中,但在 JDK8 中已修复。您的值可以正确地表示为 BigDecimal
s,并且应该正确运行,但不正确。
通过the source code of BigDecimal
追溯,第2585行,this.precision()
为1,this.scale
为-2147483647
。 this.precision() - this.scale
因此溢出,下面的溢出没有正确处理
这个错误 has been fixed in JDK8 by doing the subtraction in long
arithmetic。
我正在测试一些涉及 BigDecimal
的代码的边界条件,我注意到当使用字符串 "1e2147483647"
初始化 BigDecimal
时,它的行为异常。它的值似乎介于 0
和 1e-2147483647
之间。当我尝试调用 intValue()
时,我得到一个 NegativeArraySizeException
。我应该注意到 2147483647
是我系统上整数的最大值。我是不是做错了什么,或者这是 BigDecimal
的问题?
BigDecimal test = new BigDecimal("1e2147483647");
test.compareTo(new BigDecimal(0)); //Returns 1
test.compareTo(new BigDecimal("1e-2147483647")); //Returns -1
test.intValue(); //Throws NegativeArraySizeException
不,您似乎有一个合法的错误。该错误出现在 JDK7 中,但在 JDK8 中已修复。您的值可以正确地表示为 BigDecimal
s,并且应该正确运行,但不正确。
通过the source code of BigDecimal
追溯,第2585行,this.precision()
为1,this.scale
为-2147483647
。 this.precision() - this.scale
因此溢出,下面的溢出没有正确处理
这个错误 has been fixed in JDK8 by doing the subtraction in long
arithmetic。