我正在上课的贷款计算器。我快完成了,但是唯一缺少的是如何舍入INTEREST_RATE而不是$ 298.95833333333337,我希望获得$ 298.96。但是我不知道如何。
输入您的旧原则=
25000
输入您当前的付款=
450
上一个余额:$ 25000.0
付款:$ 450.0
已付利息:$ 151.04166666666666
支付的原理:$ 298.95833333333337
新校长:24701.041666666668
import java.util.Scanner;
public class LoanCalculator {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* Declaration Section
*
*/
Scanner keyboard = new Scanner(System.in);
double INTEREST_RATE;
double currentPayment;
double oldPrincipal;
double interestPaid;
double principalPaid;
double newPrincipal;
/**
* Process Section
*
*/
System.out.println("Enter your old Principle = ");
oldPrincipal = keyboard.nextDouble();
System.out.println("Enter your current payment = ");
currentPayment = keyboard.nextDouble();
INTEREST_RATE = 7.25 / 100.0; //fix this
interestPaid = oldPrincipal * INTEREST_RATE / 12;
principalPaid = currentPayment - interestPaid;
newPrincipal = oldPrincipal - principalPaid;
/**
* Output Section
*
* */
System.out.println("Previous Balance: " + "$"+ oldPrincipal);
System.out.println("Payment: " + "$"+ currentPayment);
System.out.println("Interest Paid: " + "$"+ interestPaid);
System.out.println("Principle Paid: " + "$"+ principalPaid);
System.out.println("New Principal: " + "$"+ newPrincipal);
}//Main()
}//LoanCalculator
最佳答案
编辑:我们应该使用BigDecimal类进行财务计算。
BigDecimal类具有内置的格式化程序,因此我添加了它。
编辑:
甚至按照@Basil Bourque的建议将舍入模式更改为一半。
public class LoanCalculator {public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
BigDecimal INTEREST_RATE, currentPayment, oldPrincipal, interestPaid, principalPaid, newPrincipal, month;
System.out.println("Enter your old Principle = ");
oldPrincipal = keyboard.nextBigDecimal();
System.out.println("Enter your current payment = ");
currentPayment = keyboard.nextBigDecimal();
NumberFormat formatter = new DecimalFormat("#0.00");
INTEREST_RATE = new BigDecimal(7.25 / 100.0);
formatter.format(INTEREST_RATE);//only format
month = new BigDecimal(12);
interestPaid = INTEREST_RATE.multiply(oldPrincipal);
interestPaid = interestPaid.divide(month, 2);
principalPaid = currentPayment.subtract(interestPaid);
newPrincipal = oldPrincipal.subtract(principalPaid);
System.out.println("Previous Balance: " + "$" + oldPrincipal);
System.out.println("Payment: " + "$" + currentPayment);
System.out.println("Interest Paid: " + "$" + interestPaid.setScale(2, RoundingMode.HALF_EVEN)
+ " $" + formatter.format(interestPaid));
System.out.println("Principle Paid: " + "$" + principalPaid.setScale(2, RoundingMode.HALF_EVEN)
+ " $" + formatter.format(principalPaid));
System.out.println("New Principal: " + "$" + newPrincipal.setScale(2, RoundingMode.HALF_EVEN)
+ " $" + formatter.format(newPrincipal));}}