How do I get my Java program to round? [duplicate] - java

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 7 years ago.
I want my Java program to round numbers off to two decimals. I've been looking at my class materials and I can't find a solution. Here's the code
import java.io.*;
import java.util.*;
public class prog58i
{
public static void main (String[] args)
{
//input
System.out.print("the amount I wish to borrow is? ");
Scanner a = new Scanner(System.in);
double borrow = a.nextDouble();
//Shows amount of money someone wants to borrow
System.out.print("The loan rate I can get is? ");
Scanner b = new Scanner(System.in);
double rate = b.nextDouble();
//Shows loan interest rate
System.out.print("The number of months it will take me to pay of this loan is? ");
Scanner c = new Scanner(System.in);
double months = c.nextDouble();
//Shows months loan will be taken out
//The Math Part
double MP = borrow * (rate/1200) * (Math.pow((1+rate/1200), months)) / (Math.pow((1+rate/1200), months)- 1);
double intrest = (MP * months) - borrow;
double repaid = (MP*months);
//Output
System.out.print( "My monthly payments will be $" +MP +"\n");
System.out.print( "Total Interest Paid is $" +intrest +"\n");
System.out.print( "Total Amount Paid is $" +repaid +"\n");
}
}
I'm more looking for a tutorial or just some advice on how to do it myself.

if you just need to round the output, you can do
System.out.printf("My monthly payments will be $%.2f%n", MP);
System.out.printf("Total Interest Paid is $%.2f%n", intrest);
System.out.printf("Total Amount Paid is $%.2f%n", repaid);

Related

How to use System.out.printf() to display output of number to only two decimal places?

I am creating my first java program for the class. The purpose of the program is to calculate interest for deposit for year one and year two. My issue comes when the code outputs the final totals. The last two lines are supposed to use System.out.printf(). I keep getting the error Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'i'. How do I correct this?
public static void main(String... args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello World!");
//declares variables
double interest = 0;
double balance = 0;
double deposit = 0;
double secondYearBalance = 0;
double secondYearInterest = 0;
//displays welcome message
System.out.println("Welcome to George's Interest Calculator");
//prompts user for input
System.out.println("Please enter your initial deposit:");
deposit = keyboard.nextInt();
//Finds outs interest interest earned on deposit
interest = deposit * TAXRATE;
//Finds out the amount of the balance
balance = deposit + interest;
//finds out second year balance
secondYearInterest = balance * TAXRATE;
secondYearBalance = secondYearInterest + balance;
//Outputs totals
System.out.printf("Your balance after one year with a 4.9% interest rate is $%7.2f %n", balance);
System.out.printf("Your balance after two years with a 4.9% interest rate is $%7.2f %n", secondYearBalance);
System.out.println();
}
The % symbol is used in a printf string for 'put a variable here'.
That's problematic when you write 4.9% interest rate because java thinks that % i is you saying: "a variable goes here". The fix is trivial; a double % is how you write a single percent. Thus:
System.out.printf("Your balance after one year with a 4.9%% interest rate is $%7.2f %n", balance);

Exception in thread "main" java.lang.NumberFormatException: For input string: "0.06"

I have been trying to make a simple program in eclipse for a school project, but I keep getting this after I enter my interest rate. I am relatively new to coding and programming in general, and java is new to me as of this month so any help is appreciated. The code is this:
import java.util.Calendar;
import java.util.Locale;
import java.util.Scanner;
public class Interest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
//Input ============================
System.out.println("Initial loan total:"); //cost
String cost;
cost = in.nextLine();
System.out.println("Down payment:"); //down
String down;
down = in.nextLine();
System.out.println("Length of term:"); //term
String term;
term = in.nextLine();
System.out.println("Interest rate (decimal form):"); //rate
String rate;
rate = in.nextLine();
int principle1 = Integer.parseInt(cost) - Integer.parseInt(down);
String hundred;
hundred = "100";
int interest = Integer.parseInt(rate) * Integer.parseInt(hundred);
//Output ===========================
Calendar c = Calendar.getInstance();
System.out.format("%tB %td, %tY", c,c,c);
System.out.println("");
System.out.println("The initial cost of the loan is $" + cost);
System.out.println("The down payment is $" + down);
System.out.println("The principle is $" + principle1);
System.out.println("The term is " + term + " months");
System.out.println("The interest rate is " + interest + "%");
System.out.println("The monthly patments are $");
in.close();
}
}
When I run the program it lets me put in the initial loan, down payment and length of term but as soon as I put in 0.06 for the interest rate it gives me the error message. I would also like to point out that I have a limited understanding of how the math in my code works.
the problem is that you are trying to parse 0.06 to Integer and 0.06 is float.
use Float.parseFloat(rate); and your interest should be a float too float interest

Java Computing Monthly Payments Loops

I have a question for yall, I am using loops for the following program and I cant understand how to make it so it displays each payment per month,
You are going to write a program which will display the payment schedule for a loan given an interest rate and the number of payments.
Prompt the user for a loan amount, the annual interest rate, number of years to pay off the loan. First, you will calculate the monthly payment using a formula below. Then you will write a loop displaying the monthly payment breakdown: interest amount, principal applied to the loan, and the balance of the loan.
For a 1 year loan (12 monthly payments) for $10,000 at 7%, the payment breakdown looks like the following:
monthly payment = 865.27
payment:1 interest: 58.33 principal: 806.93 balance: 9193.07
HERE IS THE ISSUE ABOVE I CANT GET IT TO DISPLAY THE AMOUNT OF PAYMENTS FOR (x) MONTHS AND FOR IT TO DISPLAY THE REST OF THE INFO WITH IT.
import java.text.NumberFormat;
import java.util.Scanner;
public class MothlyPay {
public static double calculateMonthlyPayment(
int loanAmount, int termInYears, double interestRate) {
// Convert interest rate into a decimal
// eg. 6.5% = 0.065
interestRate /= 100.0;
// Monthly interest rate
// is the yearly rate divided by 12
double monthlyRate = interestRate / 12.0;
// The length of the term in months
// is the number of years times 12
int termInMonths = termInYears * 12;
// Calculate the monthly payment
// Typically this formula is provided so
// we won't go into the details
// The Math.pow() method is used calculate values raised to a power
double monthlyPayment =
(loanAmount*monthlyRate) /
(1-Math.pow(1+monthlyRate, -termInMonths));
return monthlyPayment;
}
public static void main(String[] args) {
// Scanner is a great class for getting
// console input from the user
Scanner scanner = new Scanner(System.in);
// Prompt user for details of loan
System.out.print("Enter loan amount: ");
int loanAmount = scanner.nextInt();
System.out.print("Enter loan term (in years): ");
int termInYears = scanner.nextInt();
System.out.print("Enter interest rate: ");
double interestRate = scanner.nextDouble();
// Display details of loan
double monthlyPayment = calculateMonthlyPayment(loanAmount, termInYears, interestRate);
double totalPayed = 0;
int month = 1;
double loanAmountRemaining;
// NumberFormat is useful for formatting numbers
// In our case we'll use it for
// formatting currency and percentage values
while(totalPayed <= loanAmount){
totalPayed = totalPayed + monthlyPayment;
double totalLoanAmount = loanAmount + interestRate;
loanAmountRemaining = totalLoanAmount - totalPayed;
month ++;
}
if(monthlyPayment > loanAmount)
totalPayed = totalPayed + loanAmountRemaining;
}
// Display details of the loan
//HERE IS THE ISSUE BELOW, I CANT GET IT TO DISPLAY THE AMOUNT OF PAYMENTS FOR (x) MONTHS AND FOR IT TO DISPLAY THE REST OF THE INFO WITH IT FOR THE FOLLOWING VARIABLE LISTED IN THE PRINTF STATEMENT.
System.out.printf("%9s %9s %9s %9s\n", "monthlypayment", "interestRate", "loanAmount", "loanAmountRemaining");
}
//When user put in the loan amount, interest rate, months, It needs display like the picture below.
Right now, you don't have your print statement in any specific method, meaning it won't be called. I would recommend putting it in your main method, and then running a loop to find and print your values.

How to implement a particular maths formula in Java?

package methods;
import java.util.Scanner;
/**
*
* #author Billy
*/
public class Methods {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
double Loanamount; // Loan amount from user
double Aintrate; // User's annual interest rate
double months; // Number of months on loan
double monp; // Monthly payment
double Mintrate; // Monthly interest rate
double n; // The number of payments
// declare an instance of Scanner to read the datastream from the keyboard.
Scanner kb = new Scanner(System.in);
// Get user's loan amount
System.out.print("Please enter your total loan amount: ");
Loanamount = kb.nextDouble();
// Get user's interest rate
System.out.print("Please enter your annual interest rate as a decimal: ");
Aintrate = kb.nextDouble();
// Get user's number of months
System.out.print("Please enter the number of months left on your loan: ");
months = kb.nextDouble();
// Calculate montly interest rate
Mintrate = ((Aintrate / 12));
System.out.println("Your monthly interest rate is " + " " + Mintrate);
// Calculate number of payments
n = ((months * 12));
// Calculate monthly payment
My next job is to find out the monthly payment using this formula.
M = P [ i(1 + i)^n ] / [ (1 + i)^n – 1]
Where
M = monthly mortgage payment
P = The amount borrowed (Loanamount)
i = Monthly interest rate (Mintrate)
n = the number of payments
I tried the following but I just cant figure it out
monp = Loanamount [Mintrate(1+ Mintrate)^n] / [(1+ Mintrate)^n-1 ];
You need to use Math.pow effectivley here.
Try using following in your code
monp = Loanamount*(Mintrate*Math.pow((1+ Mintrate),n)) / (Math.pow((1+ Mintrate),n-1 ) ;
Math.pow is what you need instead of ^. Also you can't use [ or ]. You have to use parenthesis ( and ).
More math functions can be found at:
http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
The method for ^ is called Math.pow(double a, double b); in Java.
Where a is the number to be raised b times.
Your formula would then look like monp = Loanamount Math.pow((Mintrate(1+ Mintrate), n)) / (Math.pow((1+ Mintrate), n-1));
Reference
You need to call Math.pow(double,double)
OR you could import the required class as..
import static java.lang.Math.pow;
and then use pow() function

Simple calculation not displaying correct value

I wrote a simple program that receives several inputs and it does a future investment calculation.
However, for some reason, when I enter the following values:
investment = 1
interest = 5
year = 1
I get Your future value is 65.34496113081846 when it should be 1.05.
import java.util.*;
public class futurevalue
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("This program will calculate your future investment value");
System.out.println("Enter investment amount: ");
double investment = sc.nextDouble();
System.out.println("Enter annual interest amount: ");
double interest = sc.nextDouble();
System.out.println("Enter number of years: ");
int year = sc.nextInt();
double futureValue = investment * (Math.pow(1 + interest, year*12));
System.out.println("Your future value is " + futureValue);
}
}
Found my mistake. I divided my interest twice.
You should divide your interest by 100.
How is the interest rate being entered? Should you not divide it by 100 before adding 1 inside Math.pow?
Example: Monthly interest = 1%, if you enter 1, your Math.pow would be Math.pow(1+1, year*12) which would be incorrect.
Yes, your main error is not dividing by 100 to convert from percents to proportion, but you have another error:
If you have an APR of 5% the formula you need to use to calculate a compounding monthly interest isn't 5%/12, it's
(0.05+1)^(1/12)-1
And then the return for that investment ends up being:
1 * ( (0.05+1)^(1/12)-1 +1 )^(1 * 12) =
1 * ( (0.05+1)^(1/12) )^(12) =
1 * ( 0.05+1 ) = 1.05
exactly.

Categories