Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# Mortgage Calculator displays too many numbers after the decimal

Posted on 2006-07-18
Medium Priority
314 Views
I am trying to display a whole number with two digits after the decimal place such as \$125.25 and not \$125.123456789
Here is my program and it works just fine, I simply need some help implementing this piece of code right here:
DecimalFormat decimalPlaces = new DecimalFormat("\$0.00");
Here is my program and any help will be greatly appreciated !!

//Importing the java classes associated with this program
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

public class MultiMortgage

{
//MultiMortgage is the existing function
public static void main(String[] args)

{

DecimalFormat decimalPlaces = new DecimalFormat("\$0.00");

//hard code the value of the mortgage
double mortgage = 200000.00;
//hard code in the yearly interst rate
double[][] yearsYearlyRate =

{
{ 7, 15, 30 },
{ 5.35, 5.5, 5.75 }

};

//then code in the value for the number of times a year mulitplied by
// the amoutn paid each time
double[][] monthsMonthlyRt =

{
{
yearsYearlyRate[0][0] * 12, yearsYearlyRate[0][1] * 12,
yearsYearlyRate[0][2] * 12
},
{
yearsYearlyRate[1][0] / 1200, yearsYearlyRate[1][1] / 1200,
yearsYearlyRate[1][2] / 1200
}
};

for (int i = 2; i < 3; i++)

{

//Call the method
double payment = calPayment(monthsMonthlyRt[1][i], monthsMonthlyRt[0][i], mortgage);

// Display the monthly payment

System.out.println("\nMortgage Amount \tTerm \t\tRate \t\tPayment");
System.out.println("\$200,000 \t\t" + yearsYearlyRate[0][i] + " years\t"
+ yearsYearlyRate[1][i] + "%\t\t" + payment);

System.out.println("\nPayment # \tMonthly Interest Paid \t\tRemaining Loan Balance");

// Call the method
interestBalanceList(mortgage, monthsMonthlyRt[1][i], monthsMonthlyRt[0][i], payment);

}

}

// Utility method to calculate the monthly mortgage payment
// (1st error spotted)public static double calPayment(double param1, double
// param2, double mortgage);
public static double calPayment(double param1, double param2, double mortgage) {

double tmp = 1 + ( param1 ) ;
for ( int i = 1 ; i < param2 ; i++)
tmp = tmp * ( 1 + param1 ) ;
double monthlyPayment = mortgage * tmp * param1 / ( tmp - 1 ) ;

// Calculate the monthlyPayment of the mortgage
//double monthlyPayment = (param1 + param2 / (Math.pow((1 + param1), param2) - 1)) * mortgage;

return monthlyPayment;
}

// Utility method to list the interest paid and loan balance
public static void interestBalanceList(double mortgage, double param1, double param2,
double payment)

{

// Use the for loop to display the list
for (int i = 1; i < (param2 + 1); i++)

{

// Pause the list and go to the next month and next amount
System.out.println("Hit the 'ENTER' key to view the loan amortization.");

try

{
}      catch (Exception e)

{

}

// Calculate the monthlyInterest
double monthlyInterest = mortgage * param1;

// Calculate the loanBlance
double loanRemaining = mortgage - (payment - monthlyInterest);

// Set the value of mortgageAmount to the value of loanRemaining
mortgage = loanRemaining;

// Formate the monthlyInterest into U.S. currency
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
String str = n.format(monthlyInterest);

// Formate the loanRemaining into U.S. currency
NumberFormat num = NumberFormat.getCurrencyInstance(Locale.US);
String string = num.format(loanRemaining);

// Display the payment #, monthly interest paid and remaining loan balance

System.out.println("\n " + i + "\t\t\t" + str + "\t\t\t" + string);

}
}
}
0
Question by:waw9667
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 8
• 7
• 3
• +1

LVL 23

Expert Comment

ID: 17135436
> NumberFormat num = NumberFormat.getCurrencyInstance(Locale.US);

Since you are using this to display the number - it would display it correctly (as you expect).
0

LVL 23

Expert Comment

ID: 17135443
> System.out.println("\$200,000 \t\t" + yearsYearlyRate[0][i] + " years\t"
>                     + yearsYearlyRate[1][i] + "%\t\t" + payment);

If you want to format payment variable here, you need to do the same thing, (defining NumberFormat and using it)
0

Author Comment

ID: 17135685
I'm not sure if you've compiled what I already have or not but it's the very top line of output where the payment is exactly \$1167.1457128870982 and I would like it to read \$1167.15.  The payments on all the other lines already print out just fine.  Maybe I inserted your code into the wrong area but I was not successful.
0

LVL 23

Expert Comment

ID: 17135725
As i suggested above, you can try formatting the number:

System.out.println("\$200,000 \t\t" + yearsYearlyRate[0][i] + " years\t"
+ yearsYearlyRate[1][i] + "%\t\t" + payment);

Should be replaced with
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println("\$200,000 \t\t" + yearsYearlyRate[0][i] + " years\t"
+ yearsYearlyRate[1][i] + "%\t\t" + format.format(payment));

0

LVL 23

Accepted Solution

Ajay-Singh earned 1000 total points
ID: 17135739
> DecimalFormat decimalPlaces = new DecimalFormat("\$0.00");

This should be

DecimalFormat decimalPlaces = new DecimalFormat("Â¤#,##0.00;(Â¤#,##0.00)");

if you really want to alter the decimal places, (but by default NumberFormat.getCurrencyInstance(Locale.US); formats number upto 2 decimal places and add bracket for negative numbers)
0

Author Comment

ID: 17135848
I am becoming more confused.
0

LVL 23

Expert Comment

ID: 17135872
If you don't want to use NumberFormat.getCurrencyInstance(Locale.US); and want your custom formatting, try the above format.
But the function "NumberFormat.getCurrencyInstance(Locale.US);" returns a format that fulfills your requirement
0

Author Comment

ID: 17135905
Please forgive me for sounding like a complete idiot, but what in the world is the character to the left of the pound sign?
I have never seen this before and this simply adds to my ignorant state. Either I'm placing it inside the program wrong or just leaving something else out.
0

Author Comment

ID: 17135959
NumberFormat.getCurrencyInstance(Locale.US);

I previously posted my code.  Could you tell me where this would go inside the program.  I think that is my problem.
0

LVL 23

Expert Comment

ID: 17135972
The symbol Â¤ (\u00A4) indicates that the number format should be in currency format so that the formatter can add currency sign like \$, â‚¬ etc.

For more details, have a look to "Special Pattern Characters" section of http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormat.html
0

LVL 23

Expert Comment

ID: 17135980
as i mentioned above, it should be before System.out.println call in the main() function
0

Author Comment

ID: 17136009
NumberFormat.getCurrencyInstance(Locale.US);

I have placed this code inside the main [] in many different locations and still no luck.  Thanks for your time.
0

LVL 10

Expert Comment

ID: 17136080
waw9667 ,

just replace this,

>> System.out.println("\$200,000 \t\t" + yearsYearlyRate[0][i] + " years\t"
>>                    + yearsYearlyRate[1][i] + "%\t\t" + payment);

with
System.out.println("\$200,000 \t\t" + yearsYearlyRate[0][i] + " years\t"
+ yearsYearlyRate[1][i] + "%\t\t" + NumberFormat .getCurrencyInstance (Locale .US ) .format( payment) ) ;
0

Author Comment

ID: 17136158
This does not compile for me.  The 360 payments that are listed in this program, print out very nicely on the screen with a whole number and only two digits after the decimal but the payment on the very first line at the very top of the screen, contains a whole number and 13 digits after the decimal.  Even without any of the code that has been offered to me, the 360 payments print just fine.  It's the very very top line that I'm trying to figure out and I have yet to figure it out.  I replaced the code exactly as you suggested and I got 2 or 3 errors so I took it back out.
0

LVL 23

Expert Comment

ID: 17136286
can you post the compiler message?
0

LVL 35

Expert Comment

ID: 17136337
This (posted by mukundha_expert)

> NumberFormat .getCurrencyInstance (Locale .US ) .format( payment)

should work for the payment in the very first line. If not then I think you are doing something wrong.
0

LVL 10

Assisted Solution

mukundha_expert earned 1000 total points
ID: 17136723

Ok, here we go,
run the code below,

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

public class MultiMortgage

{

//MultiMortgage is the existing function
public static void main(String[] args)

{

DecimalFormat decimalPlaces = new DecimalFormat("\$0.00");

//hard code the value of the mortgage
double mortgage = 200000.00;
//hard code in the yearly interst rate
double[][] yearsYearlyRate =

{
{ 7, 15, 30 },
{ 5.35, 5.5, 5.75 }

};

//then code in the value for the number of times a year mulitplied by
// the amoutn paid each time
double[][] monthsMonthlyRt =

{
{
yearsYearlyRate[0][0] * 12, yearsYearlyRate[0][1] * 12,
yearsYearlyRate[0][2] * 12
},
{
yearsYearlyRate[1][0] / 1200, yearsYearlyRate[1][1] / 1200,
yearsYearlyRate[1][2] / 1200
}
};

for (int i = 2; i < 3; i++)

{

//Call the method
double payment = calPayment(monthsMonthlyRt[1][i], monthsMonthlyRt[0][i], mortgage);

// Display the monthly payment

System.out.println("\nMortgage Amount \tTerm \t\tRate \t\tPayment");
//System.out.println("\$200,000 \t\t" + yearsYearlyRate[0][i] + " years\t"
//     + yearsYearlyRate[1][i] + "%\t\t" + payment);

System.out.println("\$200,000 \t\t" + yearsYearlyRate[0][i] + " years\t"
+ yearsYearlyRate[1][i] + "%\t\t" + NumberFormat .getCurrencyInstance (Locale .US ) .format( payment) ) ;

System.out.println("\nPayment # \tMonthly Interest Paid \t\tRemaining Loan Balance");

// Call the method
interestBalanceList(mortgage, monthsMonthlyRt[1][i], monthsMonthlyRt[0][i], payment);

}

}

// Utility method to calculate the monthly mortgage payment
// (1st error spotted)public static double calPayment(double param1, double
// param2, double mortgage);
public static double calPayment(double param1, double param2, double mortgage) {

double tmp = 1 + ( param1 ) ;
for ( int i = 1 ; i < param2 ; i++)
tmp = tmp * ( 1 + param1 ) ;
double monthlyPayment = mortgage * tmp * param1 / ( tmp - 1 ) ;

// Calculate the monthlyPayment of the mortgage
//double monthlyPayment = (param1 + param2 / (Math.pow((1 + param1), param2) - 1)) * mortgage;

return monthlyPayment;
}

// Utility method to list the interest paid and loan balance
public static void interestBalanceList(double mortgage, double param1, double param2,
double payment)

{

// Use the for loop to display the list
for (int i = 1; i < (param2 + 1); i++)

{

// Pause the list and go to the next month and next amount
System.out.println("Hit the 'ENTER' key to view the loan amortization.");

try

{
}     catch (Exception e)

{

}

// Calculate the monthlyInterest
double monthlyInterest = mortgage * param1;

// Calculate the loanBlance
double loanRemaining = mortgage - (payment - monthlyInterest);

// Set the value of mortgageAmount to the value of loanRemaining
mortgage = loanRemaining;

// Formate the monthlyInterest into U.S. currency
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
String str = n.format(monthlyInterest);

// Formate the loanRemaining into U.S. currency
NumberFormat num = NumberFormat.getCurrencyInstance(Locale.US);
String string = num.format(loanRemaining);

// Display the payment #, monthly interest paid and remaining loan balance

System.out.println("\n " + i + "\t\t\t" + str + "\t\t\t" + string);

}
}

}

This will compile and run, if you still get the error post your full code and the error you are getting.,
0

Author Comment

ID: 17142604
I want to be very clear when I say that this code, even when it did not produce exactly what I wanted, did not error anywhere in the program.  This revised code, just as the previous code, does not error either, nor does it produce the payment the way I want on the very top line.  Yes, I certainly agree with you that this code compiles very nicely, however, the payment on the very top line is still 1167.1457128870982.  I'm not sure this is even worth the bother.
0

LVL 10

Expert Comment

ID: 17143787
Are you sure??
I tested and it shows only \$1,167.15.

i think you are running the older version.

create a new Java file in a different folder, compile it and run the new class file generated.
else delete all the older class files, compile the new version of java file to get the new class and run it.

0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilationâ€¦
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define â€¦
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arrâ€¦
###### Suggested Courses
Course of the Month8 days, 18 hours left to enroll