目前我正在编写一个计算数学常数的程序。但是,我在舍入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)
答案 0 :(得分:1)
请参阅ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"
基本上你可以将rounding_mode传入divide函数。见下文:
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);
}
}
}