目前,我正在编写一个程序来计算数学常数。但是,在四舍五入BigDecimals时遇到麻烦。一旦它达到一个非终止的小数(1.6),就会抛出一个错误。我认为问题是四舍五入,但是它也将其设置为正确的小数位数,但没有四舍五入。我是BigDecimals的新手,所以我可能忘记了一些东西。代码和输出如下所示。谢谢!

这是我的代码:

package goldenratio;
import java.math.*;

public class GoldenRatio {
static BigDecimal now;
static BigDecimal before;
static BigDecimal phi;
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    for(int i=1;i<=100;i++)
    {
        if(i==1)
        {
            now=BigDecimal.valueOf(1);
            before=BigDecimal.valueOf(1);
            phi=BigDecimal.valueOf(1);
        }else
        {
          phi=(now.divide(before));
          phi = phi.setScale(5, RoundingMode.HALF_UP);
          BigDecimal oldBefore = before;
          before=now;
          now=now.add(oldBefore);
        }
        System.out.println(phi);
    }
}


这是我的输出:

run:
1.00000
2.00000
1.50000
Exception in thread "main" java.lang.ArithmeticException: Non-terminating
decimal expansion; no exact representable decimal result.
  at java.math.BigDecimal.divide(BigDecimal.java:1690)
  at goldenratio.GoldenRatio.main(GoldenRatio.java:30)

最佳答案

ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

基本上,您可以将rounding_mode传递到除法函数中。见下文:

import java.math.*;

public class GoldenRatio {
    static BigDecimal now;
    static BigDecimal before;
    static BigDecimal phi;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        for (int i = 1; i <= 100; i++) {
            if (i == 1) {
                now = BigDecimal.valueOf(1);
                before = BigDecimal.valueOf(1);
                phi = BigDecimal.valueOf(1);
            } else {
                phi = (now.divide(before, 5, RoundingMode.HALF_UP));
                BigDecimal oldBefore = before;
                before = now;
                now = now.add(oldBefore);
            }
            System.out.println(phi);
        }
    }
}

09-28 10:17