Math.pow difficulty - java

When I enter 1000 for investment amount 4.25 for monthly interest rate and 1 for years, why do I get the result 4.384414858452464E11 instead of the expected 1043.34?
import java.util.Scanner;
public class FinancialApplicationFutureInvestment_13 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter investment amount: ");
int investmentAmount = input.nextInt();
System.out.println("Enter monthly interest rate: ");
double monthlyInterestRate = input.nextDouble();
System.out.println("Enter number of years");
int numOfYears = input.nextInt();
double futureInvestmentValue = investmentAmount *
(Math.pow(1 + monthlyInterestRate, numOfYears * 12));
System.out.println("Accumulated value is: " + futureInvestmentValue);
double test = Math.pow(1 + monthlyInterestRate, numOfYears * 12);
System.out.println(test);
}
}

Monthly interest rate will probably need to be entered as 0.0425

1 + monthlyInterestRate
Is monthlyInterestRate a raw factor, or is it expressed in percentage points?
Try dividing by one hundred.

the formula is
A = P(1+r/100)^n
so it should be
investmentAmount * (Math.pow(1 + (monthlyInterestRate/100), numOfYears * 12));

well, you compute 1+4.25 (5.25) as monthly interest rate, instead of 1+(4.25/100) .

you should use casting in System.out.println (double to int) --
(int)(futureInvestmentValue * 100) / 100.0

Related

I'm making a payroll using Java. Why am I getting the wrong net pay if my mathematical formulas seem correct?

I'm making a payroll calculator. The first person worked 38.00 hours with a pay rate of $8.75. The second person worked 46.50 hours with a pay rate of $17.00. It's obvious the second person worked overtime. I'm experiencing issues when calculating the net pay as well as the gross pay. The second person's net pay should be $718.89. I keep getting $140.89. The issues only happen if the person works overtime (>40). Is there a problem with my if statement? I'd like some advice. I've been learning Java for 2 weeks now, excuse the mistakes.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
final byte PERCENT = 15;
// Tax is 15%
final float taxRate = PERCENT / (float) 100;
Scanner scanner = new Scanner(System.in);
System.out.print("First Name: ");
String firstName = scanner.next().trim();
System.out.print("Last Name: ");
String lastName = scanner.next().trim();
System.out.println(lastName + ", " + firstName);
System.out.print("Pay Rate: ");
float payRate = scanner.nextFloat();
System.out.print("Hours Worked: ");
float totalHours = scanner.nextFloat();
// regular hours = total hours if less than 40
// overtime = total hours - 40
float regularPay = 0;
if (totalHours <= 40) {
regularPay = totalHours * payRate;
}
float overTimePay = 0;
if (totalHours > 40) {
overTimePay = (float) ((totalHours - 40) * 1.5 * payRate);
}
final double grossPay = (double) regularPay + (double) overTimePay;
System.out.println("Gross Pay: " + (Math.round(grossPay * 100.0) / 100.0));
final double taxAmount = grossPay * taxRate;
System.out.println("Tax Amount: " + (Math.round(taxAmount * 100.0) / 100.0));
final double netPay = grossPay - taxAmount;
System.out.println("Net Pay: " + (Math.round(netPay * 100.0) / 100.0));
}
}
if totalHours > 40, regularPay will be 0 in your code.
you should change the condition to something like this.
if totalHours > 40, first calculate regularPay for 40 hours
overtimepay should be remaining hours (totalhours -40)
your regularPay variable is only being recorded if hours<=40. You need to put something in your second if statement to set your regularPay variable. You probably want something like:
regularPay = 40*payRate;
Include this in your second if statement

Calculate sales tax according to the price

I am trying to do on the java assignment and the scenario is as follows:
A sales tax of 7% is levied on all goods and services consumed. It is also mandatory that all the price tags should include the sales tax. For example, if an item has a price tag of $107, the actual price is $100 and $7 goes to the sales tax.
Write a program using a loop to continuously input the tax-inclusive price (as "double"); compute the actual price and the sales tax (in "double"); and print the results rounded to 2 decimal places. The program shall terminate in response to input of -1; and print the total price, total actual price, and total sales tax.
However, when I try to compute the sales tax, instead of showing this:
Enter·the·tax-inclusive·price·in·dollars·(or·-1·to·end): 107
Actual·Price·is: $100.00
Sales·Tax·is: $7.00
My calculation shows this:
Enter the tax-inclusive price in dollars (or -1 to end): 107
Actual price is $99.51
Sales Tax is: $7.49
I am not sure what's wrong with my coding.
import java.util.Scanner;
public class SalesTax{
public static void main(String[] args) {
// Declare constants
final double SALES_TAX_RATE = 0.07;
final int SENTINEL = -1; // Terminating value for input
// Declare variables
double price, actualPrice, salesTax; // inputs and results
double totalPrice = 0.0, totalActualPrice = 0.0, totalSalesTax = 0.0; // to accumulate
// Read the first input to "seed" the while loop
Scanner in = new Scanner(System.in);
System.out.print("Enter the tax-inclusive price in dollars (or -1 to end): ");
price = in.nextDouble();
while (price != SENTINEL) {
// Compute the tax
salesTax = SALES_TAX_RATE * price;
actualPrice = price - salesTax;
// Accumulate into the totals
totalPrice = actualPrice + salesTax;
totalActualPrice = actualPrice + actualPrice;
totalSalesTax = salesTax + salesTax;
// Print results
System.out.println("Actual price is $" + String.format("%.2f",actualPrice));
System.out.println("Sales Tax is: $" + String.format("%.2f",salesTax));
// Read the next input
System.out.print("Enter the tax-inclusive price in dollars (or -1 to end): ");
price = in.nextDouble();
// Repeat the loop body, only if the input is not the sentinel value.
// Take note that you need to repeat these two statements inside/outside the loop!
}
// print totals
System.out.println("Total price is: " + String.format("%.2f",totalPrice));
System.out.println("Total Actual Price is: " + String.format("%.2f",totalActualPrice));
System.out.println("Total sales tax is: " + String.format("%.2f",totalSalesTax));
}
}
Any help would be appreciated. Thank you!
You're wrong with these two lines:
salesTax = SALES_TAX_RATE * price;
actualPrice = price - salesTax;
You're calculating the sales on the already-saled price, try following me:
Your price is the composition of the actualPrice and the tax on actualPrice:
price = actualPrice + SALES_TAX_RATE * actualPrice
so you can mathematically do the following passages:
price = actualPrice * (1 + SALES_TAX_RATE)
actualPrice = price / (1 + SALES_TAX_RATE)
So, try changing the assigment of actualPrice, then calculate the tax on your actualPrice:
salesTax = SALES_TAX_RATE * actualPrice;
You should calculate actual price first and with the help of that calculate sales tax rate
and instead of using this
salesTax = SALES_TAX_RATE * price; actualPrice = price - salesTax;
calculate using this:
actual_price = price / 1.07; tax_price = price - actual_price;
1.07 came from dividing tax % with 100 and adding 1 to it(you can do this to any amount of %)
I came across something similar and used this logic. You need to divide the sales tax by 100 like 7/100 with 7 being the percentage of your tax variable or you can multiply by .01 then take the result of that and add it to your variable's total value. 1% is .01 of 100%. So 7% would be .07 multiplied by your variable and added to the total you are trying to calculate. If you want precision and not rounded to the nearest integer then just set parameters on the Math.round function or don't even use it at all.
public static void solve(double meal_cost, int tip_percent, int tax_percent) {
double tip = Math.round((tip_percent * .01) * meal_cost);
double tax = Math.round((tax_percent * .01) * meal_cost);
int total_cost = (int)(meal_cost + tip + tax);
System.out.println(total_cost);
}
The problem is your sales tax calculation, try:
final double SALES_TAX_RATE = 7;
salesTax = price / (100 + SALES_TAX_RATE) * SALES_TAX_RATE;

Return to start of loop java

This is a program that lets the user enter the loan amount and loan period in number of years and displays the monthly and total payments for each interest rate starting from 5% to 8%, with an increment of 1/8.
I may have over-indulged myself here as I'm pretty new to programming, but I'm in too deep and want to figure this out.
With my current code the first line outputs correctly, displaying the rate, total and monthly. However, after that the code just continues to output the inner most loop. I need to return to the start of the loop. It would greatly be appreciated if you could point me in the right direction.
P.S. I am aware that my padding isn't in place. My biggest concern is getting the algorithm down on "paper" first, and then worrying about the beauty of it.
package loancalc194;
import java.util.Scanner;
public class LoanCalc194 {
public static void main(String[] args) {
//LOAN CALCULATOR
//user enters loan AMOUNT, loan PERIOD(years),
//output displays MONTHLY and TOTAL payments
//^displayed per 1/8 increment from 5-8% interest
Scanner in = new Scanner(System.in);
//prompt user
//retrieve loan amount and period
System.out.print("Please enter the loan amount: ");
double amount = in.nextDouble();
System.out.print("Please enter the loan period (years): ");
int period = in.nextInt();
//INTEREST LOOP///////////////////////////////////////////////////
double interest = .05000;
double inc = 0.00125;
interest = interest + inc;
double monthly = 0;
double total = 0;
System.out.println("Interest Rate\t\t\tTotal Payment\tMonthly Payment");
while (interest < .08){
//interest = interest + inc;
System.out.print(interest + "\t");
while (true){
total = (amount * period) + (interest * amount);
System.out.print("\t" + total + "\t\t");
while (true) {
monthly = ((total / period) / 12);
System.out.println(monthly);
//interest = interest + inc;
}
}
}
One loop should be enough for what you want.
Your two while(true) loops do nothing else than looping on the same values forever.
In the following code, the interest gets incremented and the new calculations computed at each loop until interest reaches your max value, this is probably what you need.
double interest = .05000;
double inc = 0.00125;
double monthly = 0;
double total = 0;
while (interest < .08){
System.out.print(interest + "\t");
total = (amount * period) + (interest * amount);
System.out.print("\t" + total + "\t\t");
monthly = ((total / period) / 12);
System.out.println(monthly);
interest = interest + inc;
}

how to get two variables to print with one in decimal form

I am very new. apologies in advance for my coding. I need to print a table that shows year and then a tab over, and then the value with a next line. The value has to be in decimal form.
I have been reading and searching and mixing my code around. I have found it for 1 variable but not for two in same line. I have tried the printf, I have tried the good ol 100 / 100.0 and I either get errors or the decimal never goes to 2 places. I do not need it rounded, just with 2 spaces after. I am obviously going wrong somewhere. I would appreciate any assistance.
import java.util.Scanner;
public class Investment1 {
public static double futureInvestmentValue(double investmentAmount, double monthlyInterestRate, int years){
double principal = 0.0;
double futureInvestmentValue = 0;
for (years = 1; years <=30; years++){
//calculate futureInvestmentValue
futureInvestmentValue = (investmentAmount * (Math.pow (1 + monthlyInterestRate, years * 12)));
System.out.print(years + "\t" + futureInvestmentValue + "\n");
}//end for
return futureInvestmentValue;
}//end futureInvestmentValue
public static void main(String[] args){
Scanner input = new Scanner (System.in);
//obtain Investment amount
System.out.print("Enter Investment amount: ");
double investmentAmount = input.nextDouble();
//obtain monthly interest rate in percentage
System.out.print("Enter annual interest rate in percentage: ");
double annualInterestRate = input.nextDouble();
double monthlyInterestRate = (annualInterestRate / 1200);
int years = 30;
System.out.println("Years\t" + "Future Value");
System.out.print(years + "\t");
System.out.print(years + "\t" + ((int)(futureInvestmentValue(investmentAmount, monthlyInterestRate, years))) + "\n");
}//end main
}//end Investment
You can use system.out.format():
System.out.format("%d \t %.2f", years, futureInvestmentValue);
you should read about format strings, heres a simple usage example:
System.out.println(String.format("%d %.2f",myint,myfloat));
myint will be printed as an integer (even if it's a floating point value) due to the use of the %d in the format string.
myfloat will be printed as a decimal number with 2 digits after the decimal point, thanks to the %f.2 part in the format string.

Reading The Calculation Wrong with math pow

am only getting the interest amount an not the amount i suppose to pay a month can you please tell me where am going wrong thanks.
import java.util.Scanner;
/**
*
* #author
*/
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 payment type:");
String period = input.next();
System.out.print("Enter Loan Length :");
int length = input.nextInt();
//proces
rate = interest / 100;
if (period.equals("monthly")) {
double n = length * 12;
payment = principal * (rate * Math.pow((1 + rate), n) / Math.pow((1 + rate), n));
System.out.printf("Your Monthly Sum is %.2f",payment);
}
}
Your error is here:
principal * rate * Math.pow((1 + rate), n) / Math.pow((1 + rate), n)
This is the same as having only principal * rate. You are saying x = b * a / a.
Replace to:
payment = principal * Math.pow((1 + rate), n);
n is the number of years, you can not do n = length / 12 to get Monthly. You should do instead:
payment = (principal * Math.pow((1 + rate), n)) / 12;
It should be
payment = principal * Math.pow((1 + rate), n);
As
A=P((1+rate/100)^n)

Categories