英文:
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.
专注分享java语言的经验与见解,让所有开发者获益!
评论