Java的Printf精度不会四舍五入。

huangapple 未分类评论45阅读模式
英文:

Java Printf precision isn't rounding

问题

我正在学习Java,并尝试使用printf(%.2f)功能将模拟储蓄账户中的数字舍入到小数点后两位。在单独使用此功能时,它可以正常工作,但在我的程序中似乎无效。以下是相关的代码部分。

public void calculateMonthlyInterest() {
    double monthlyInterest = (annualInterestRate * savingsBalance) / 12;
    savingsBalance = savingsBalance + monthlyInterest;
    System.out.printf("The new balance is $%.2f%n", savingsBalance);
}

但输出结果并没有将小数点后的数字进行舍入。例如: "The new balance is $2006.6666666666667"

我不明白为什么在其他地方能够正常工作,但在这里却无效?

有人建议我提供输入值,所以这里是它们:annualInterestRate = 0.04,savingsBalance = 2000。运行后,输出结果如上所示。

英文:

I'm learning Java and trying to round numbers in a mock savings account to 2 decimal places using the printf(%.2f) feature. Trying it on it's own the feature works fine, but in my program it just doesn't seem to work. Here is the relevant code.

public void calculateMonthlyInterest() {
      double monthlyInterest = (annualInterestRate * savingsBalance)/12;
      savingsBalance = savingsBalance + monthlyInterest;
      System.out.printf("The new balance is $%.2f%n", savingsBalance);
}

It outputs without rounding the decimal places. Ex: "The new balance is $2006.6666666666667"

I don't understand why it works elsewhere, but not here?

I was suggested to give my input values, so here they are: annualInterestRate = .04, savingsBalance = 2000. After it runs through, the output is as listed above.

huangapple
  • 本文由 发表于 2020年4月8日 04:30:14
  • 转载请务必保留本文链接:https://java.coder-hub.com/61088894.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定