This question already has answers here:
How to print a float with 2 decimal places in Java?
(18 answers)
Closed 2 years ago.
I need this specific line to be 2 decimal points.
System.out.println(i + "\t\t" + interest + "\t\t" + principal + "\t\t" + balance);
my entire code is
import java.util.Scanner;
public class assignment5dot22 {
public static void main(String[] args) {
int numberOfYears;
double loanAmount;
double annualInterest;
double monthlyInterest;
double monthlyPayment;
double principal;
double balance;
double interest;
Scanner input = new Scanner(System.in);
System.out.print("Loan Amount: ");
loanAmount = input.nextDouble();
System.out.print("Number of Years: ");
numberOfYears = input.nextInt();
System.out.print("Annual Interest Rate: ");
annualInterest = input.nextDouble();
monthlyInterest = annualInterest / 1200;
monthlyPayment = loanAmount*monthlyInterest / (1 - (Math.pow(1 / (1 + monthlyInterest),
numberOfYears * 12)));
balance = loanAmount;
System.out.println("Monthly Payment: "
+ (monthlyPayment * 100) / 100.0);
System.out.println("Total Payment: "
+ (monthlyPayment * 12 * numberOfYears * 100) / 100.0);
System.out.println("\nPayment#\tInterest\tPrincipal\tBalance");
for (int i = 1; i <= numberOfYears * 12; i++) {
interest = (monthlyInterest * balance);
principal = ((monthlyPayment - interest)*100) / 100.0;
balance = ((balance - principal) * 100) / 100.0;
System.out.println(i + "\t\t" + interest + "\t\t" + principal + "\t\t" + balance);
}
}
}
I'd suggest trying to use String.format() for your output.
e.g.
System.out.println(String.format("%d \t\t %.2f \t\t %.2f \t\t %.2f", i, interest, principal, balance);
String.format allows you use %d and %.2f to explicitly state the format of your data (integer and float respectively)
In these situations you could use String.format or directly use System.out.printf() like so:
System.out.printf("%d \t\t %.2f \t\t %.2f \t\t %.2f\n", i, interest, principal, balance);
For these cases it's more readable and concise.
Related
I am trying the write the formula in the image using Java. However, I get the wrong output. This is what I am so far for the computation.
Assume Input is: Loan Amount = 50000 and Length = 3 year.
My output is currently "676.08" for 'Monthly Payment' and "25661.0" for "Total Interest Payment".
"Monthly payment" should be "1764.03" and "Total Interest Payment" should be "13505.05".
Code is:
//Program that displays the interest rate and monthly payment based on the loan amount and length of loan the user inputs.
import java.util.Scanner;
public class bankLoanSelection{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
//Declarations.
double interestRate;
final double n = 12;
//Generates an account number in the range of 1 to 1000.
int accountnumber = (int)(Math.random() * 1000)+1;
//User input
System.out.print("Enter Loan Amount: $");
double L = input.nextDouble();
System.out.print("Length of Loan (years): ");
double i = input.nextDouble();
//selection structure using if and if-else statements.
if (L <= 1000)
interestRate = .0825;
else if (L <= 5000)
interestRate = .0935;
else if (L <= 10000)
interestRate = .1045;
else interestRate = .1625;
//Computations.
double MonthlyPayment = L * (interestRate / n) * Math.pow(1 + interestRate / n, i * n) / Math.pow(1 + interestRate / n, i * n) - 1;
double TotalAmountOfLoan = MonthlyPayment * i * n;
double TotalInterest = L - TotalAmountOfLoan;
//Output.
System.out.println("Account Number: #" + accountnumber);
System.out.println("Loan Amount: $" + L);
System.out.println("Loan Length (years): " + i);
System.out.println("Interest Rate: " + interestRate * 100 + "%");
System.out.printf("Total Monthly Payment: $%.2f%n", MonthlyPayment); //Rounds second decimal
System.out.println("Total Interest Payments: $" + TotalInterest);
}
}
You have to put round parentheses between condition.
It should be:
double MonthlyPayment = L * ((interestRate / n) * Math.pow(1 + interestRate / n, i * n))
/ (Math.pow(1 + interestRate / n, i * n) - 1);
You need to correct the arrangement of brackets in the denominator, the correct formula would be:
double numerator = L * (interestRate / n) * Math.pow(1 + interestRate / n, i * n)
double denominator = Math.pow(1 + interestRate / n, i * n) - 1;
double MonthlyPayment = numerator / denominator;
Try to break the problem into smaller units to solve.
Problem with my code for calculator - output values not correct
Here is my code, any response would be appreciated.
import java.util.Scanner;
public class Savings {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
//ask for initial amount
System.out.print("What is the initial savings amount? ");
double initialAmount = console.nextDouble();
// ask for number of months
System.out.print("What is the number of months to save? ");
int months = console.nextInt();
//ask for interest rate
System.out.print("What is the annual interest rate? ");
double interestRate = console.nextDouble();
//calculate total
double monthlyInterest = ((interestRate/100)*(1/12));
double number1 = (monthlyInterest + 1);
double number2 = Math.pow(number1, months);
double total = (initialAmount*number2);
System.out.println("$" + initialAmount + ", saved for " + months + " months at " + interestRate + "% will be valued at $" + total);
console.close();
}
}
final value ends up being the same value as initial
Change this:
double monthlyInterest = ((interestRate/100)*(1/12));
to
double monthlyInterest = (interestRate / 100) * (1.0 / 12.0);
You're trying to do integer division in floating-point context, so in monthlyInterest you are essentially multiplying interestRate / 100 with 0.
Add d with the numbers to convert them into double and keep the decimal value, this way -
double monthlyInterest = ((interestRate/100d)*(1/12d));
If you do 1/12 with integers, the output will be 0, but with 1/12d it will be 0.08333333333333333
Also, you can get rid of the extra parenthesis -
double monthlyInterest = (interestRate/100d)*(1/12d);
...
double number1 = monthlyInterest + 1;
...
double total = initialAmount * number2;
So I am writing a program that does some financial calculations. However, because I used double for my data types, the cents are not rounded. Here is the source code:
public class CentRoundingTest {
public static void main(String[] args) {
System.out.println("TextLab03, Student Version\n");
double principle = 259000;
double annualRate = 5.75;
double numYears = 30;
// Calculates the number of total months in the 30 years which is the
// number of monthly payments.
double numMonths = numYears * 12;
// Calculates the monthly interest based on the annual interest.
double monthlyInterest = 5.75 / 100 / 12;
// Calculates the monthly payment.
double monthlyPayment = (((monthlyInterest * Math.pow(
(1 + monthlyInterest), numMonths)) / (Math.pow(
(1 + monthlyInterest), numMonths) - 1)))
* principle;
// calculates the total amount paid with interest for the 30 year time.
// period.
double totalPayment = monthlyPayment * numMonths;
// Calculates the total interest that will accrue on the principle in 30
// years.
double totalInterest = monthlyPayment * numMonths - principle;
System.out.println("Principle: $" + principle);
System.out.println("Annual Rate: " + annualRate + "%");
System.out.println("Number of years: " + numYears);
System.out.println("Monthly Payment: $" + monthlyPayment);
System.out.println("Total Payments: $" + totalPayment);
System.out.println("Total Interest: $" + totalInterest);
}
}
My instructor also does not want this to use the DecimalFormat class. I was thinking to obtain the cents value by doing: variable-Math.floor(variable), and then rounding that amount to the nearest hundredth, then adding that together.
Without using the JDK-provided library classes that exist for this purpose (and would normally be used), the pseudocode for rounding arithmetically is:
multiply by 100, giving you cents
add (or subtract if the number is negative) 0.5, so the next step rounds to the nearest cent
cast to int, which truncates the decimal part
divide by 100d, giving you dollars)
Now go write some code.
Well, if you cannot use the DecimalFormat class, you could use printf():
TextLab03, Student Version
Principle : $259,000.00
Annual Rate : 5.75%
Number of years : 30.00
Monthly Payment : $1,511.45
Total Payments : $544,123.33
Total Interest : $285,123.33
public class CentRoundingTest {
public static void main(String[] args) {
System.out.println("TextLab03, Student Version\n");
double principle = 259000;
double annualRate = 5.75;
double numYears = 30;
// Calculates the number of total months in the 30 years which is the
// number of monthly payments.
double numMonths = numYears * 12;
// Calculates the monthly interest based on the annual interest.
double monthlyInterest = 5.75 / 100 / 12;
// Calculates the monthly payment.
double monthlyPayment = (((monthlyInterest * Math.pow(
(1 + monthlyInterest), numMonths)) / (Math.pow(
(1 + monthlyInterest), numMonths) - 1)))
* principle;
// calculates the total amount paid with interest for the 30 year time.
// period.
double totalPayment = monthlyPayment * numMonths;
// Calculates the total interest that will accrue on the principle in 30
// years.
double totalInterest = monthlyPayment * numMonths - principle;
printAmount("Principle", principle);
printPercent("Annual Rate", annualRate);
printCount("Number of years", numYears);
printAmount("Monthly Payment", monthlyPayment);
printAmount("Total Payments", totalPayment);
printAmount("Total Interest", totalInterest);
}
public static void printPercent(String label, double percentage) {
//System.out.printf("%-16s: %,.2f%%%n", label, percentage);
printNumber(label, percentage, "", "%", 16);
}
public static void printCount(String label, double count) {
//System.out.printf("%-16s: %,.2f%n", label, count);
printNumber(label, count, "", "", 16);
}
public static void printAmount(String label, double amount) {
//System.out.printf("%-16s: $%,.2f%n", label, amount);
printNumber(label, amount, "$", "", 16);
}
public static void printNumber(String label, double value, String prefix, String suffix, int labelWidth) {
String format = String.format("%%-%ds: %%s%%,.2f%%s%%n", labelWidth);
System.out.printf(format, label, prefix, value, suffix);
}
}
I need to have an outcome like this:
example the user input are principal = 2000, term=6, rate=2%
Period Interest Total Interest Total Balanced<br>
1 6.66 6.66 2006.60
2 6.69 13.35 2013.35
3 6.71 20.06 2020.06
4 6.74 26.80 2026.80
5 6.75 33.55 2033.55
6 6.78 40.33 2040.33
My code is:
import java.io.*;
public class interest
{
public static void main(String[] args)throws Exception
{
BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in));
float p, t, r, total;
int a = 1;
System.out.println("Enter the amount deposited: ");
p = Integer.parseInt(bufferedreader.readLine());
System.out.println("Enter the number of term: ");
t = Integer.parseInt(bufferedreader.readLine());
System.out.println("Enter the interest rate(%): ");
r = Integer.parseInt(bufferedreader.readLine());
System.out.println("Period \t Interest Total Interest Total Balance");
while ( a <= t)
{
System.out.print(" " + a + "\t ");
a++;
{
float R = (float) (r/100)/t;
float interest = (float) p * R;
float totalInt = (float) interest ;
total = p + totalInt;
System.out.println(interest + "\t\t" + totalInt + "\t " + total);
}
}
}
}
but the outcome turns up like this:
Period Interest Total Interest Total Balance
1 6.6666665 6.6666665 2006.6666
2 6.6666665 6.6666665 2006.6666
3 6.6666665 6.6666665 2006.6666
4 6.6666665 6.6666665 2006.6666
5 6.6666665 6.6666665 2006.6666
6 6.6666665 6.6666665 2006.6666
Move your totalInt declaration outside of your while declaration.
You're currently resetting it in every loop, thus it's not actually your total interest but your current interest.
You need to do: totalInt += interest; in the loop.
And you don't need to cast interest to a float again for the increment, as it's already declared as a float.
Also it might be cleaner to do total += interest rather than starting out from your base deposit and incrementing it with your totalInt every time.
And as to your last issue, the formatting, just do something along the lines of:
System.out.printf("%.2f \t\t %.2f \t\t %.2f\n", interest, totalInt, total);
Or take a look at DecimalFormat
I am assuming the question is about the output formating
System.out.printf("%.2f \t\t %.2f \t\t %.2f\n", interest, totalInt, total);
Hi keep float interest before while loop like this
float interest=0;
while ( a <= t)
{
System.out.print(" " + a + "\t ");
a++;
{
float R = (float) (r/100)/t;
interest = interest + (float) p * R;
float totalInt = (float) interest ;
total = p + totalInt;
System.out.println(interest + "\t\t" + totalInt + "\t " + total);
}
}
}
Now Execute it you will get the required output please like if you are satisfied.
Thank You
I think what you want is, change the first line to:
float p, t, r, total, R, interest, totalInt;
and remove float declaration inside loop
I have tried to do a simple math calculation for a formula involving variables. However, an error pops up in the compiler indicating that the variable types don't match. I have tried casting and changing the variable types, but they do not work. How do I fix this without destroying the basic format of my code.
I am not experienced at Java, so any pointers will help.
Here is the code. It is for a money conversion program. The error is in the second part of the code, the else part.
import java.util.Scanner;
public class MConvert
{
public static void main (String[] args)
{
int penny, nickel, dime, quarter, halfDollar, dollar, fiveDollar, tenDollar, twentyDollar, fiftyDollar, hundredDollar;
//can sub $ sign for dollar in variable, convention otherwise
double totalMoney;
Scanner scan = new Scanner (System.in);
System.out.println ("Are you converting to the total? If so, type true. \nIf you are converting from the total, then type false.");
boolean TotalorNot = true;
TotalorNot = scan.nextBoolean();
if (TotalorNot) {
System.out.println ("Type in the number of one-hundred dollar bills.");
hundredDollar = scan.nextInt();
System.out.println ("Type in the number of fifty dollar bills.");
fiftyDollar = scan.nextInt();
System.out.println ("Type in the number of twenty dollar bills.");
twentyDollar = scan.nextInt();
System.out.println ("Type in the number of ten dollar bills.");
tenDollar = scan.nextInt();
System.out.println ("Type in the number of five dollar bills.");
fiveDollar = scan.nextInt();
System.out.println ("Type in the number of one dollar bills or coins.");
dollar = scan.nextInt();
System.out.println ("Type in the number of half-dollar coins.");
halfDollar = scan.nextInt();
System.out.println ("Type in the number of quarter-dollar coins.");
quarter = scan.nextInt();
System.out.println ("Type in the number of dimes.");
dime = scan.nextInt();
System.out.println ("Type in the number of nickels.");
nickel = scan.nextInt();
System.out.println ("Type in the number of pennies coins.");
penny = scan.nextInt();
totalMoney = (hundredDollar * 100) + (fiftyDollar * 50) + (twentyDollar * 20) + (tenDollar * 10) + (fiveDollar * 5) + (dollar * 1) + ((double)halfDollar * 0.5) + ((double)quarter * 0.25) + ((double)dime * 0.1) + ((double)nickel * 0.05) + ((double)penny * 0.01);
System.out.println ("Here is total monetary value of the bills and coins you entered: " + totalMoney);
} else {
System.out.println ("Type in the total monetary value:");
totalMoney = scan.nextDouble();
hundredDollar = ((int)totalMoney / 100);
fiftyDollar = ((int)totalMoney - (hundredDollar * 100)) / 50;
twentyDollar = ((int)totalMoney - (fiftyDollar * 50)) / 20;
tenDollar = ((int)totalMoney - (twentyDollar * 20)) / 10;
fiveDollar = ((int)totalMoney - (tenDollar * 10)) / 5;
dollar = ((int)totalMoney - (fiveDollar * 5)) / 1;
(double) halfDollar = (totalMoney - (dollar * 1)) / 0.5;
quarter = ((int)totalMoney - (halfDollar * 0.5)) / 0.25;
dime = ((int)totalMoney - (quarter * 0.25)) / 0.1;
nickel = ((int)totalMoney - (dime * 0.1)) / 0.05;
penny = ((int)totalMoney - (nickel * 0.05)) / 0.01;
System.out.println (hundredDollar + " hundred dollar bills");
System.out.println (fiftyDollar + " fifty dollar bills");
System.out.println (twentyDollar + " twenty dollar bills");
System.out.println (tenDollar + " ten dollar bills");
System.out.println (fiveDollar + " five dollar bills");
System.out.println (dollar + " one dollar bills or coins");
System.out.println (halfDollar + " half-dollar coins");
System.out.println (quarter + " quarter-dollar coins");
System.out.println (dime + " dimes");
System.out.println (nickel + " nickel");
System.out.println (penny + " penny");
}
}
}
(double) halfDollar = (totalMoney - (dollar * 1)) / 0.5;
Is entirely wrong , first remove this instruction.
Also change your code with below lines.
quarter = (int)((totalMoney - (halfDollar * 0.5)) / 0.25);
dime = (int) ((totalMoney - (quarter * 0.25)) / 0.1);
nickel =(int)( (totalMoney - (dime * 0.1)) / 0.05);
penny = (int)((totalMoney - (nickel * 0.05)) / 0.01);
You also need to improve logic of your code, I can clearly see it do not serve what you want to achieve.
At this line
((int)totalMoney - (tenDollar * 10)) / 5;
the cast is applied to just totalMoney
to cast the value of whole expression you must do this
(int)(totalMoney - (tenDollar * 10)) / 5);
The problem is in the following line:
(double) halfDollar = (totalMoney - (dollar * 1)) / 0.5;
What is the meaning of the (double) here? You cannot cast the left side of a variable assignment (the variable itself) to a double. The variable is declared to be an int, and that cannot be changed. Never.
This line compiles (but may be incorrect concerning semantics):
halfDollar = (int) ((totalMoney - (dollar * 1)) / 0.5);
Apart from that: I don't think, the program does, what you want it to do...
(double) halfDollar = (totalMoney - (dollar * 1)) / 0.5;
What are you trying to achieve with the double cast on the halfDollar. Remove that first. It took me 5 mins to find out why there were so many red lines in your code.
Next, you can do a simple case like this:-
halfDollar = (int)((totalMoney - (dollar * 1)) / 0.5);
But its not advisable to cast double values to int as you may tend to lose a lot of decimal data. Why not simple have all penny, nickel, dime, quarter, halfDollar, dollar, fiveDollar, tenDollar,twentyDollar, fiftyDollar, hundredDollar; as double itself?