double a = Double.parseDouble(amount.getText());
double r = Double.parseDouble(rate.getText())/100;
double y = Double.parseDouble(years.getText());
double m=y*12;
double simple =a+(a*r*y);
double compound = a * Math.pow(1+ r, m);
String d = String.format("%.2f", simple);
String d1 = String.format("%.2f", simple/12);
String d2 = String.format("%.2f", compound);
int x=1;
while(x<=m && type.getSelectedItem().equals("Simple")) {
monthly1.append(String.valueOf(x+(". ")+d1+("\n")));
x++;
total1.setText(String.valueOf(d));
}
if (type.getSelectedItem().equals("Compound")){
for (int month=1;month<=m;month++){
monthly2.append(String.valueOf(month+(". ")+d2+"\n"));
total2.setText(String.valueOf(d2));
}
}
Simple interest works fine but compound monthly doesn't. I tried
amount:1000 rate:5 years 3.
And got
1. 5791.82
2. 5791.82
3. 5791.82
up to 60.
And I want it to show how much I have to pay monthly.
You only seem to calculate compound once, at the very beginning of your code. I'd create a method calculateCompoundInterest(int month) and then call this from within your loop like so:
for (int month=1; month <= m; month++) {
String monthlyAmount = String.format("%.2f", calculateCompoundInterest(month));
monthly2.append(String.valueOf(month+(". ")+monthlyAmount+"\n"));
total2.setText(String.valueOf(d2));
}
You are calculating monthly interest incorrectly.
formula a* Math.pow(1+r,y) needs to be applied like a* Math.pow(1+r/12,y*12) if compounded monthly. you need to convert your rate as well to use in the formula.
Please see this for more explanation of formula.
Here is the code to help you started:
for (int month=1;month<=m;month++){
d2 = String.format("%.2f",a * Math.pow(1+ r/12, month));
monthly2.append(String.valueOf(month+(". ")+d2+"\n"));
total2.setText(String.valueOf(d2));
}
Related
This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 3 years ago.
import java.text.NumberFormat;
public class Mortgage {
public static void main(String[] args) {
int p = 1000000;
NumberFormat percent = NumberFormat.getPercentInstance();
double r = Double.parseDouble(percent.format(3.92*12));
int t = (int)(r);
double n;
n = Math.pow(30,12);
int f = (int) Math.floor(n);
int a =(1+t)^f;
int b = (a-1);
int c = (t*a)/b;
int m = p*c;
NumberFormat currency = NumberFormat.getCurrencyInstance();
String result = currency.format(m);
System.out.println(result);
}
}
I have tried to changed r to int but I still got exception. What am I not writing correctly?
You use NumberFormat.getPercentInstance() to format your number. This adds a % symbol and other number formatting (depending on your default locale). Then the Double.parseDouble(...) call fails because the number is not a pure double number.
There is no need to format and parse the number, you can just assign it directly to the double variable as it is a constant anyways.
I see several problems.
double n;
n = Math.pow(30,12);
int f = (int) Math.floor(n);
30 to the 12th power. That does not make sense for a 30 year mortgage Did you mean 30*12 for 360 pay periods. Or possibly Math.pow(30,1+montlyRate) where monthlyRate = (AR/100)/12 and AR = annual rate).
int a =(1+t)^f;
The operator ^ is not power but an exclusive OR. You probably didn't want that either.
I recommend you check out this Wiki entry on computing Mortage Payments
Here is one way to do calculate it and then display it per month.
double in = 5.5; // annual percentage rate
double mo_rate = (in / 100) / 12.; // monthly rate
double PV = 400_000.; // present value (cost of the house).
double f = Math.pow(1 + mo_rate, 360); // factor resulting from the linear
// expansion
double payment = mo_rate * PV * f / (f - 1); // Monthly payment including
// interest and
// principal
System.out.printf("Monthly payment is %7.2f%n", payment);
Note: different banks and/or countries may do it differently.
The answer is in the exception java.lang.NumberFormatException: For input string: "4,704%"
percent.format(3.92*12) returns the String : 4 704 % and this can't be parsed to double, because of the space and the % symbol, you just need to multiply it by 100 to consider it as a percentage
double r = 3.92 * 12 * 100;
As you're using only ints you fall into the int division problem and you'll get a 0 at the end, so you may use at leat one double ot cast one durint the division
int a = (1 + t) ^ f;
double b = (a - 1);
double c = (t * a) / b;
double m = p * c;
// OR
int a = (1 + t) ^ f;
int b = (a - 1);
double c = (t * a) / (double) b;
double m = p * c;
Also ^ is thr XOR symbol, to use power computation :
double a = Math.pow(1+t, f);
For the result, it depends on r:
double r = 3.92 * 12 * 100; gives -10 308,38 €
double r = 3.92 * 12; gives 999 998,95 €
And use names that explain what the variable is, as much as possible
my assignment is to calculate the number of years it takes to reach $5000 if you start with $2500 with 7.5% interest. The calculation should be 10 years, but it outputs 11 years. This might be a simple syntax error, but I've been trying to fix this for the past 2 hours with no luck.
final double principle = 2500.00;
double accrued = 0;
final double interest = 0.075;
int year = 0;
double interest1 = 1.0 + interest;
while (accrued < 5000.00)
{
accrued = principle * Math.pow(interest1, year);
year++;
}
System.out.printf("It would take %d years to reach at least $5000 if you start with $2,500 with 7.5%% compound interest.", year);
Try this :
final double principle = 2500.00;
double accrued = 0;
final double interest = 0.075;
int year = 0;
double interest1 = 1.0 + interest;
while (accrued < 5000.00)
{
year++;
accrued = principle * Math.pow(interest1, year);
}
System.out.printf("It would take %d years to reach at least $5000 if you start with $2,500 with 7.5%% compound interest.", year);
I'm supposed to calculate
using Simpson's rule, with 4 sub intervals.
I surely do not want do it by hand so I have tried to write that algorithm in Java.
The formula for Simpson's rule is
And here is my code:
import java.util.Scanner;
import java.util.Locale;
public class Simpson {
public static void main(String[] args) {
Scanner input = new Scanner(System.in).useLocale(Locale.US);
//e= 2.718281828459045 to copy paste
System.out.println("Interval a: ");
double aInt = input.nextDouble();
System.out.println("Interval b: ");
double bInt = input.nextDouble();
System.out.println("How many sub intervals: ");
double teilInt = input.nextDouble();
double intervaldistance = (bInt-aInt)/teilInt;
System.out.println("h = "+"("+bInt+"-"+aInt+") / "+teilInt+ " = "+intervaldistance);
double total = 0;
System.out.println("");
double totalSum=0;
for(double i=0; i<teilInt; i++) {
bInt = aInt+intervaldistance;
printInterval(aInt, bInt);
total = prod1(aInt, bInt);
total = total*prod2(aInt, bInt);
aInt = bInt;
System.out.println(total);
totalSum=totalSum+total;
total=0;
}
System.out.println("");
System.out.println("Result: "+totalSum);
}
static double prod1(double a, double b) { // first product of simpson rule; (b-a) / 6
double res1 = (b-a)/6;
return res1;
}
static double prod2(double a, double b) { // second pproduct of simpson rule
double res2 = Math.log(a)+4*Math.log((a+b)/2)+Math.log(b);
return res2;
}
static void printInterval(double a, double b) {
System.out.println("");
System.out.println("["+a+"; "+b+"]");
}
}
Output for 4 sub intervals:
[1.0; 1.4295704571147612]
0.08130646125926948
[1.4295704571147612; 1.8591409142295223]
0.21241421690076787
[1.8591409142295223; 2.2887113713442835]
0.31257532785558795
[2.2887113713442835; 2.7182818284590446]
0.39368288949073565
Result: 0.9999788955063609
Now If I compare my solution with other online calculators (http://www.emathhelp.net/calculators/calculus-2/simpsons-rule-calculator/?f=ln+%28x%29&a=1&b=e&n=4&steps=on), it differs.. But I don't see why mine should be wrong.
My solution is 0.9999788955063609, online solution is 0.999707944567103
Maybe there is a mistake I made? But I have double checked everything and couldn't find.
You may be accumulating the rounding error by doing b_n = a_{n} + interval many times.
Instead you could be using an inductive approach, where you say a_n = a_0 + n*interval, since this only involves introducing a rounding error once.
I will test with actual numbers to confirm and flesh out the answer in a little bit, but in the meantime you can watch this explanation about accumulation of error from handmade hero
PS. As a bonus, you get to watch an excerpt from handmade hero!
UPDATE: I had a look at your link. While the problem I described above does apply, the difference in precision is small (you'll get the answer 0.9999788955063612 instead). The reason for the discrepancy in your case is that the formula used in your online calculator is a slightly different variant in terms of notation, which treats the interval [a,b] as 2h. In other words, your 4 intervals is equivalent to 8 intervals in their calculation.
If you put 8 rectangles in that webpage you'll get the same result as the (more accurate) number here:
Answer: 0.999978895506362.
See a better explanation of the notation used on that webpage here
I changed your delta calculation to the top to so that you don't calculate the delta over and over again. You were also not applying the right multipliers for the odd and even factors, as well as not applying the right formula for deltaX since it has to be: ((a-b)/n) /3
double deltaX = ((bInt-aInt)/teilInt)/3;
for(int i=0; i<=teilInt; i++) { //changed to <= to include the last interval
bInt = aInt+intervaldistance;
printInterval(aInt, bInt);
total = prod2(aInt, bInt, i+1, teilInt); //added the current interval and n. The interval is +1 to work well with the even and odds
totalSum += total;
aInt = bInt;
System.out.println(total);
}
System.out.println("");
System.out.println("Result: "+ (totalSum*deltaX)); //multiplication with deltaX is now here
To account for the right factor of f(x) i changed the prod2 to:
static double prod2(double a, double b, int interval, double n) {
int multiplier = 1;
if (interval > 0 && interval <= n){
//applying the right multiplier to f(x) given the current interval
multiplier = (interval % 2 == 0) ? 4 : 2;
}
return multiplier * Math.log(a);
}
Now it yields the correct result:
How to get the double value that is only two digit after decimal point.
For example if the a = 190253.80846153846
then the result value should be like a = 190253.80
Try:
I have try with this:
public static DecimalFormat twoDForm = new DecimalFormat("#0.00");
in code
a = Double.parseDouble(twoDForm.format(((a))));
But i got the value like 190253.81 instead of that i want 190253.80
So what should i have to change for it ??
Because Math.round() Returns the closest int to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type int.
Use Math.floor()
Example
public static double roundMyData(double Rval, int numberOfDigitsAfterDecimal) {
double p = (float)Math.pow(10,numberOfDigitsAfterDecimal);
Rval = Rval * p;
double tmp = Math.floor(Rval);
System.out.println("~~~~~~tmp~~~~~"+tmp);
return (double)tmp/p;
}
Complete Source code
class ZiggyTest2{
public static void main(String[] args) {
double num = 190253.80846153846;
double round = roundMyData(num,2);
System.out.println("Rounded data: " + round);
}
public static double roundMyData(double Rval, int numberOfDigitsAfterDecimal) {
double p = (float)Math.pow(10,numberOfDigitsAfterDecimal);
Rval = Rval * p;
double tmp = Math.floor(Rval);
System.out.println("~~~~~~tmp~~~~~"+tmp);
return (double)tmp/p;
}
}
Try this,
make a object of BigDecimal
double a = 190253.80846153846;
BigDecimal bd = new BigDecimal(a);
BigDecimal res = bd.setScale(2, RoundingMode.DOWN);
System.out.println("" + res.toPlainString());
With no libraries:
a = (float) (((int)(a * 100)) / 100.0f);
or, for double:
a = (double) (((int)(a * 100)) / 100.0);
i think that is going to round of the value, check this
(float)Math.round(value * 100) / 100
from this link round of decimal number
or this example
Following code works for me.
public static double round(double value, int places) {
//here 2 means 2 places after decimal
long factor = (long) Math.pow(10, 2);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
double dValue = 10.12345;
try{
String str = Double.toString(dValue*100);`
str = str.split("[.]")[0];
dValue = Double.parseDouble(str)/100;
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(dValue);
Use this code. You can get the desired output you want.
Here is another way to write it that is similar to Shabbir's ^ but I think is easier to read. I actually wanted to round it; if it showed .349, I wanted to see .35 - but if you don't want that then you can use Math.floor in place of my Math.round:
public static double round(double time){
time = Math.round(100*time);
return time /= 100;
}
Here is my complete code: I am working on a program to find 3 random 1 min time intervals in a given time segment, for a research project im working on.
import java.lang.*;
import java.util.*;
class time{
public static void main (String[] args){
int time = Integer.parseInt(args[0]);
System.out.println("time is: "+time);
//randomly select one eligible start time among many
//the time must not start at the end, a full min is needed from times given
time = time - 1;
double start1 = Math.random()*time;
System.out.println(start1);
start1 = round(start1);
System.out.println(start1);
}
public static double round(double time){
time = Math.round(100*time);
return time /= 100;
}
}
to run it, with current output:
[bharthur#unix2 edu]$ java time 12
time is: 12
10.757832858914
10.76
[bharthur#unix2 edu]$ java time 12
time is: 12
0.043720864837211715
0.04
I am sort of a Newbie to this forum and to Java. I am having a difficult time trying to find a way to ask the user to enter more than one loan to compare from steps D down. I need to be able to ask the user for a different interest rate and number of years for the amount they entered in step A. So if they entered 10 then I would have to ask them 10 times for an interest rate and years and output it in a table format using tabs. Any help is much appreciated. Thanks in advance.
Edit: Thank you so much for your help! I updated the code.
//A. Enter the Number Of Loans to compare
String numberOfLoansString = JOptionPane.showInputDialog("Enter the amount of loans to compare:");
//Convert numberOfLoansString to int
int numberOfLoans = Integer.parseInt(numberOfLoansString);
//B. Enter the Amount/Selling Price of Home
String loanAmountString = JOptionPane.showInputDialog("Enter the loan amount:");
//Convert loanAmountString to double
double loanAmount = Double.parseDouble(loanAmountString);
//C. Enter the Down Payment on the Home
String downPaymentString = JOptionPane.showInputDialog("Enter the down payment on the Home:");
double downPayment = Double.parseDouble(downPaymentString);
//D. Ask the following for as many number of loans they wish to compare
//D1 Get the interest rate
double[] anualInterestRatesArray = new double[numberOfLoans];
double[] monthlyInterestRateArray = new double[numberOfLoans];
int[] numberOfYearsArray = new int[numberOfLoans];
double[] monthlyPaymentArray = new double[numberOfLoans];
double[] totalPaymentArray = new double[numberOfLoans];
for (int i=0; i < numberOfLoans; i++)
{
String annualInterestRateString = JOptionPane.showInputDialog("Enter the interest rate:");
double annualInterestRate = Double.parseDouble(annualInterestRateString);
anualInterestRatesArray[i] = (annualInterestRate);
//Obtain monthly interest rate
double monthlyInterestRate = annualInterestRate / 1200;
monthlyInterestRateArray[i] = (monthlyInterestRate);
//D2 Get the number of years
String numberOfYearsString = JOptionPane.showInputDialog("Enter the number of years:");
int numberOfYears = Integer.parseInt(numberOfYearsString);
numberOfYearsArray[i] = (numberOfYears);
//Calculate monthly payment
double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
//Format to keep monthlyPayment two digits after the decimal point
monthlyPayment = (int)(monthlyPayment * 100) / 100.0;
//Store monthlyPayment values in an array
monthlyPaymentArray[i] = (monthlyPayment);
//Calculate total Payment
double totalPayment = monthlyPaymentArray[i] * numberOfYears * 12;
//Format to keep totalPayment two digits after the decimal point
totalPayment = (int)(totalPayment * 100) / 100.0;
totalPaymentArray[i] = (totalPayment);
}
You need to do all the repeated processing logic inside a loop such as for( ... ) loop. Use an array to store different values for the number of loans.
Use for loops for this.
P.S : You can use other loops [while, do-while] as well.
An example for using for loop
int numberOfLoans = Integer.parseInt(numberOfLoansString);
//section of code which shouldnt be repeated here outside the loop.
for( int i = 0; i < numberOfLoans ; i++ )
{
//Write Step D here , because you want it to be repeated
}
You probably need to use arrays and loops. Use arrays to store all the values entered and a loop to get the values.
double[] anualInterestRates = new double[numberOfLoans];
double[] monthlyInterestRates = new double[numberOfLoans];
int[] numberOfyears = new int[numberOfLoans];
Then you can loop and ask for each loan values:
for(int i= 0; i < numberOfLoans; i++){
//get the anual interest rate
anualInterestRates[i] = the anual interets rate gotten
//etc
}
Now you have 3 arrays of values. You can use a second loop to calculate the output and display.