我正在开发一个贷款计算器项目。目标是根据客户的信用评分改变利率。 if(finalScore <=550) 工作正常,并将每月付款打印到小数点后两位,就像我想要的那样。我遇到的问题是,当我进入下一个 if 语句“if(finalScore >550 && FinalScore <=680)”时,它将错误地打印每月付款。输出看起来类似于 147.04938.19,仅作为示例。
我尝试将 printf 中的 %.2f 更改为 %.2d,它解决了问题,但引发了非法格式异常。
这里有什么建议吗?
if(finalScore <= 550) {}
if (mortgage.equals(mlType)){}
if (lYears == 30) {
double interestRate = mIR550[0]/100 + pRate;
double monthlyRate = interestRate / 12.0;
int termInMonths = 360;
double monthlyPayments = ((mlAmount*monthlyRate)
/(1-Math.pow(1+monthlyRate, -termInMonths)));
System.out.printf("%.2f", monthlyPayments);
//prints fine here in format xxx.xx
正确输出示例:
Please enter Credit Score:
550
Loan Type Mortgage:
Mortgage
Enter Years:
30
Enter Loan Amount:
20000
___________________________________
147.03
BUILD SUCCESSFUL (total time: 2 minutes 24 seconds)
错误输出的示例
Please enter Credit Score:
680
Loan Type Mortgage:
Mortgage
Enter Years:
30
Enter Loan Amount:
20000
___________________________________
147.03125.10
BUILD SUCCESSFUL (total time: 30 seconds)
出现问题的代码
if(finalScore >550 && finalScore <=680) {
if (mortgage.equals(mlType)){
if (lYears == 30) {
double interestRate = mIR680[0]/100 + pRate;
double monthlyRate = interestRate / 12.0;
int termInMonths = 360;
double monthlyPayments = ((mlAmount*monthlyRate)
/(1-Math.pow(1+monthlyRate, -termInMonths)));
System.out.printf("%.2f", monthlyPayments);
// output returns answer formatted xxx.xxxxx.xx not sure
why?
最佳答案
你有两个 if-then-else-if 链;因此可能是 System.out.printf 的两倍。
原因是右大括号位于:
if (finalScore <= 550) {
}
您可能想包含第一个 if 链。
然后 printf 没有打印换行符,因此当打印 1.23 和 4.56 时,会打印 1.234.56。换行符如下:
System.out.printf("%.2f%n", monthlyPayments);
您的 IDE 可能有一个 Format 命令,这应该会有所帮助。
关于java - 在 if 语句的第二级之后无法将输出打印到正确的小数点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43550931/