zoukankan      html  css  js  c++  java
  • java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result异常的解决方法

    转载:https://www.cnblogs.com/YangJavaer/p/5897754.html

    场景描述#

    今天在写一个JAVA程序的时候出现了异常:java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result。
    发现报错的语句是:

    foo.divide(bar));

    解决方法#

    原来JAVA中如果用BigDecimal做除法的时候一定要在divide方法中传递第二个参数,定义精确到小数点后几位,否则在不整除的情况下,结果是无限循环小数时,就会抛出以上异常。

    foo.divide(bar, 2, BigDecimal.ROUND_HALF_UP);

    源码#

    注意这个BigDecimal的divide方法有两个重载的方法,一个是传两个参数的,一个是传三个参数的:

    两个参数的方法:

    @param divisor value by which this {@code BigDecimal} is to be divided. 传入除数

    @param roundingMode rounding mode to apply. 传入round的模式

    三个参数的方法:

    @param divisor value by which this {@code BigDecimal} is to be divided. 传入除数
    @param scale scale of the {@code BigDecimal} quotient to be returned. 传入精度
    @param roundingMode rounding mode to apply. 传入round的模式

  • 相关阅读:
    ASP.NET 2.0的页面缓存功能介绍
    第五课 主定理
    HDU 1051 Wooden Sticks
    一行代码让浏览器变编辑器
    算法概论习题1001Forest
    第七课 寻找强连通分量
    8223. Tiling a Grid With Dominoes
    迷宫
    第八课 最小生成树之Kruskal
    解决 Ubuntu 12.04 无法调节屏幕亮度的问题
  • 原文地址:https://www.cnblogs.com/brithToSpring/p/13743437.html
Copyright © 2011-2022 走看看