Link to home
Start Free TrialLog in
Avatar of waw9667
waw9667

asked on

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);

        }
    }
}
Avatar of Ajay-Singh
Ajay-Singh

> NumberFormat num = NumberFormat.getCurrencyInstance(Locale.US);

Since you are using this to display the number - it would display it correctly (as you expect).
> 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)
Avatar of waw9667

ASKER

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.  
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));

ASKER CERTIFIED SOLUTION
Avatar of Ajay-Singh
Ajay-Singh

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of waw9667

ASKER

I am becoming more confused.
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
Avatar of waw9667

ASKER

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.
Avatar of waw9667

ASKER

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.
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
as i mentioned above, it should be before System.out.println call in the main() function
Avatar of waw9667

ASKER

                 NumberFormat.getCurrencyInstance(Locale.US);

I have placed this code inside the main [] in many different locations and still no luck.  Thanks for your time.
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) ) ;
Avatar of waw9667

ASKER

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.
can you post the compiler message?
Avatar of girionis
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.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of waw9667

ASKER

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.
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.