Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 327
  • Last Modified:

Mortgage Calculator displays too many numbers after the decimal

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
waw9667
Asked:
waw9667
  • 8
  • 7
  • 3
  • +1
2 Solutions
 
Ajay-SinghCommented:
> NumberFormat num = NumberFormat.getCurrencyInstance(Locale.US);

Since you are using this to display the number - it would display it correctly (as you expect).
0
 
Ajay-SinghCommented:
> 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
 
waw9667Author Commented:
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
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
Ajay-SinghCommented:
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
 
Ajay-SinghCommented:
> 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
 
waw9667Author Commented:
I am becoming more confused.
0
 
Ajay-SinghCommented:
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
 
waw9667Author Commented:
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
 
waw9667Author Commented:
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
 
Ajay-SinghCommented:
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
 
Ajay-SinghCommented:
as i mentioned above, it should be before System.out.println call in the main() function
0
 
waw9667Author Commented:
                 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
 
mukundha_expertCommented:
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
 
waw9667Author Commented:
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
 
Ajay-SinghCommented:
can you post the compiler message?
0
 
girionisCommented:
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
 
mukundha_expertCommented:

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
 
waw9667Author Commented:
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
 
mukundha_expertCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 8
  • 7
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now