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);
}
}
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;
Here's the textbook problem:
A certain bank offers 6.5% interest on savings accounts, compounded
annually. Create a table that shows how much money a person will
accumulate over a period of 25 years, assuming that the person makes
an initial investment of $1000 and deposits $100 each year after the
first. Your table should indicate for each year the current balance,
the interest, the new deposit, and the new balance.
This is my code. It is correct:
public void compoundAnnual() {
double investment = 1000;
int year = 25;
double newDeposit = 0;
double newBalance;
double interestRate = 6.5;
double interest;
double deposit = 0;
System.out.println("Year Interest New Deposit New Balance");
System.out.println("------------------------------------------------------");
for (int i = 1; i <= year; i++) {
if (i == 1)
{
newDeposit = investment;
}
newBalance = newDeposit * Math.pow((1 + (interestRate/100)), 1);
interest = newBalance - newDeposit;
System.out.printf("%1d %10.2f %20.2f %22.2f \n ", i, interest, newDeposit, newBalance);
newDeposit = newBalance + 100;
}
}
However, when finding the newBalance I am confused why
Math.pow((1 + (interestRate/100)), 1);
is correct.
Why wouldn't
Math.pow((1 + (interestRate), 1);
be correct if interestRate was set to 0.65? When I set interestRate equal to 0.65 the output for this is wrong and I don't understand why. Wouldn't they be the same thing?
Why wouldn't ... be correct if interestRate was set to 0.65?
Because 0.65 corresponds to 65% interest.
Try 0.065 (= 6.5 / 100).
(Note that this is nothing specific to programming, it's just arithmetic).
interestRate should be 0.065 in your case not 6.5, because 6.5/100=.065.If you hard code interestRate as 6.5 you won't get expected output.
Try giving
interestRate =.065
it will work fine.
There is no tax on the first 20% of salary entered. i.e for 20000..it would tax for 16000 with 10% on 15000 and 20% on the remaining 1000 which would be 1700 total tax. My program incorrectly outputs 14500....
import java.util.*;
public class taxable {
public static void main (String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Enter your salary:");
double salary=in.nextDouble();
double taxDue=0;
double tempTaxDue=0;
if (salary < 15000) {
System.out.println("No tax applicable");
}else if
(salary >=15000 && salary <20000) {
taxDue=(15000*0.1);
}else if
(salary >=20000 && salary <=35000) {
tempTaxDue=(salary*0.8);
taxDue=15000*0.1+tempTaxDue-15000*0.2;
}else if
(salary > 35000) {
tempTaxDue=salary*0.8;
taxDue=(15000*0.1)+(20000*0.2)+(tempTaxDue-35000*0.35);
taxDue=(salary*0.8)+(20000*0.2)+(salary-35000*0.35);
}
System.out.printf("The amount of tax due is: " + taxDue + " ");
double avTaxRate;
avTaxRate=taxDue/salary*100;
System.out.printf("The average tax rate: " + avTaxRate + "%%");
}
}
When dividing integer values, always check for floating point division - 10/100 will be 0 by Java integer division terms, 10.0/100 circumcises this.
To get 10% out of something either divide it by 10.0 or multiply by 0.1.
taxDue = 15000 * 0.1;
But the biggest hidden problem here is you shouldn't use double to represent money. Use BigDecimal instead.
Why? Just for fun, let's calculate the 10% taxes over 15001?
double dValue = 15001;
double dTaxes = 15001 * 0.1;
System.out.println("Taxes with double: " + dTaxes);
// Taxes with double: 1500.1000000000001
Precision error -> Small, but it is there 0.0000000000001.
BigDecimal to the rescue:
BigDecimal value = new BigDecimal("15001");
BigDecimal taxes = value.multiply(new BigDecimal("0.1"));
System.out.println("Taxes with BigDecimal: " + taxes);
// Taxes with BigDecimal: 1500.1
Working example.
You have to use casting when you trying to assign to double variable some division, instead:
taxDue=15000*(10/100);
smt as make one of divisor double value:
taxDue = 15000.0 * (10.0 / 100);
am not getting this program to display my instalments correctly can I please get some help thanks......
package Loops;
import java.util.Scanner;
/**
*
*
*/
public class program {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//variabled decleared
double rate;
double payment;
//input
System.out.print("Enter Loan Amount:");
double principal = input.nextDouble();
System.out.print("Enter Annual Interest:");
double interest = input.nextDouble();
System.out.print("Total payments per year:");//12=monthly,4= quartely,2=semi-annually and 1=annually
double period = input.nextDouble();
System.out.print("Enter Loan Length :");
int length = input.nextInt();
//proces
double n = period * length;
rate = interest / 100;
double monthly_rate = rate / period;
payment = principal * (principal * (monthly_rate * Math.pow((1 + monthly_rate), n)));
System.out.printf("Your Monthly sum is %.2f", payment);
}
}
principal = 50000; //Redacted. Eating my words.
period = 4;
length = 4;
n = 16;
rate = 0.085;
monthly_rate = 0.085 / 16 = 0.0053125;
payment = 50000 * 50000 * 0.0053125 * (1 + 0.0053125) ^ 16;
= 2.5x10^9 * 0.0053125 * 1.088;
= Something remainingly massive
Basically... your formula is wrong. Wouldn't you need to divide by the power quotient? Where is your source on that formula?
payment = principal * (rate + (rate / ( Math.pow(1 + rate, n) - 1) ) );
Source
Example:
payment = 50000*(0.085+(0.085/(1.085^16-1)))
= 5830.68
Try this for your formula:
//this is how much a monthly payment is
payment = (rate + (rate / ((Math.pow(1 + rate), n) -1)) * principal
This is based off one of the first google results for the formula. Please post the results and expected answer if it is wrong.
I'm pretty sure your formula is just off, as you stated above that there should be a denominator in the equation.
You can use r* Math.pow ((1+r),n) to calculate the numerator and part of the denominator