Solved

Mortgage Calculator displays too many numbers after the decimal

Posted on 2006-07-18
22
271 Views
Last Modified: 2010-03-31
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

            {                                    
                System.in.read();
            }      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
Comment
Question by:waw9667
  • 8
  • 7
  • 3
  • +1
22 Comments
 
LVL 23

Expert Comment

by:Ajay-Singh
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

by:Ajay-Singh
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

by:waw9667
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

by:Ajay-Singh
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

by:
Ajay-Singh earned 250 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

by:waw9667
ID: 17135848
I am becoming more confused.
0
 
LVL 23

Expert Comment

by:Ajay-Singh
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

by:waw9667
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

by:waw9667
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
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 23

Expert Comment

by:Ajay-Singh
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

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

Author Comment

by:waw9667
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

by:mukundha_expert
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

by:waw9667
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

by:Ajay-Singh
ID: 17136286
can you post the compiler message?
0
 
LVL 35

Expert Comment

by:girionis
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

by:mukundha_expert
mukundha_expert earned 250 total points
ID: 17136723

Ok, here we go,
run the code below,
i have commented out your code and added one new line,


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

            {                              
                System.in.read();
            }     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

by:waw9667
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

by:mukundha_expert
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
The viewer will learn how to implement Singleton Design Pattern in Java.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now