I know how to print using the printf method, but can't for the life of me get it to round to two decimal places using a dialog box.
import javax.swing.JOptionPane; public class Program6 { public static void main(String[] args) { //declare variables double loanAmount, annualInterestRate, monthlyPayment, monthlyInterestRate, monthlyInterest, totalPaid; int month; //promt user to enter amount borrowed String loanAmountString = JOptionPane.showInputDialog (null, "Enter the amount to be borrowed in dollars"); loanAmount = Double.parseDouble(loanAmountString); //prompt user to enter annual interest String annualInterestRateString = JOptionPane.showInputDialog (null, "Enter the annual interest rate, eg 12 percent"); annualInterestRate = Double.parseDouble(annualInterestRateString); annualInterestRate = (annualInterestRate / 100); //calculate monthly interest rate monthlyInterestRate = annualInterestRate / 12; //calculate monthly interest payment monthlyInterest = loanAmount * monthlyInterestRate; //display monthly interest JOptionPane.showMessageDialog(null, "The Monthly interest is " + monthlyInterest); //promt user to enter amount to be paid each month String monthlyPaymentString = JOptionPane.showInputDialog (null, "Enter the amount to be paid each month. " + "Amount must be greater than monthly interest."); monthlyPayment = Double.parseDouble(monthlyPaymentString); //parse double totalPaid = 0.00f; month = 0; //begin first loop while (monthlyPayment <= monthlyInterest) { String newMonthlyPaymentString = JOptionPane.showInputDialog (null, "Your payment does not cover the interest on your loan. " + "Please enter a larger amount for your monthly payment."); monthlyPayment = Double.parseDouble(newMonthlyPaymentString); } double loanAmountRemaining = loanAmount; //begin second loop while (loanAmount != 0) { totalPaid += monthlyPayment; monthlyInterest = loanAmountRemaining * monthlyInterestRate; loanAmount += monthlyInterest; loanAmountRemaining = (loanAmount - totalPaid); month++; if (monthlyPayment > (loanAmountRemaining)) { totalPaid += loanAmountRemaining; loanAmount = 0; month++; } } //display message that loan has been paid String.format("%.2f", totalPaid); JOptionPane.showMessageDialog (null,"Congradulations! You have paid off your loan. Total amount paid is $" + totalPaid); } }
//display message that loan has been paid
String.format("%.2f", totalPaid);
JOptionPane.showMessageDialog
(null,"Congradulations! You have paid off your loan. Total amount paid is $"
+ totalPaid);
}
}
The last part is the part i want limited to 2 decimal places.