java 即使除以 100 也会发生“非终止小数扩展;没有精确可表示的小数结果”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17819058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Non-terminating decimal expansion; no exact representable decimal result" happens even when divide by 100
提问by Kazi Islam
My java code is running on HP-UX hpdev B.11.23 U ia64 and sometimes it will produce the following exception: java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
我的 java 代码在 HP-UX hpdev B.11.23 U ia64 上运行,有时会产生以下异常:java.lang.ArithmeticException:非终止十进制扩展;没有精确的可表示的十进制结果。
The code that causes it:
导致它的代码:
BigDecimal p_Change = (BigDecimal)record.get("P_CHNG");
p_Change.divide(new BigDecimal(100));
record is simple a Collection of column values from a sql query.p_change comes from a table in an Oracle database where the column is NUMBER(10,2).
记录很简单,来自 sql 查询的列值集合。p_change 来自 Oracle 数据库中的一个表,其中该列是 NUMBER(10,2)。
I understand why this happens.The frequency is random, it will divide fine with the same data sometimes. I am just wondering if this has something to do with the hardware.
我明白为什么会发生这种情况。频率是随机的,有时会用相同的数据很好地划分。我只是想知道这是否与硬件有关。
回答by James Grammatikos
Could you do a system.out on your value for p_Change?
你能对 p_Change 的值做一个 system.out 吗?
BigDecimal p_Change = new BigDecimal(Math.PI);
System.out.println(p_Change.divide(new BigDecimal(100)));
// yields this 0.03141592653589793115997963468544185161590576171875
It's identical to your code, with just the substitution of p_Change with pi
它与您的代码相同,只是将 p_Change 替换为 pi
The issue probably has to deal with you not entering a rounding mode. Try using
问题可能与您没有进入舍入模式有关。尝试使用
p_Change.divide(new BigDecimal(100), BigDecimal.ROUND_HALF_UP);