HTML and CSS Reference

In-Depth Information

Creating the monthlyPmt() User-Defined Function
The monthlyPmt()

function is a user-defined function that calculates the monthly payment amount. The

JavaScript code for the monthlyPmt() function is shown in Table 10-18.

Table 10-18 Code for monthlyPmt() User-Defined Function

Line

Code

67

function monthlyPmt(loanAmt,loanRate,loanYears) {

68

var interestRate = loanRate/1200

69

var Pmts = loanYears * 12

70

var Amnt = loanAmt * (interestRate / (1 - (1 /

Math.pow(1+interestRate,Pmts))))

return Amnt.toFixed(2)

71

}

72

Math Object

The Math object cannot

be used to create other

objects. Most of the

properties of the Math

object return preset

values. Other properties

of the Math object really

are methods and act as

functions.

Line 67 declares the monthlyPmt() function. Line 68 determines the monthly

interest rate percentage by dividing the annual rate by 1200. The result is assigned to the

interestRate (interest rate) variable. Line 69 determines the number of monthly payments

on the loan, by multiplying the number of years in the loan by 12. The resulting value is

assigned to the Pmts variable.

Line 70 is the formula for calculating a monthly payment based on the amount of

the loan, the monthly interest percentage, and the number of monthly payments. The

mathematical representation of the formula is:

loan amount * (monthly interest rate / (1 - (1 /(1 + monthly

interest rate)
number of payments
)))

JavaScript, however, does not use typical programming language symbols

to represent exponentiation in code. Instead, to calculate the expression

(1 + monthly interest rate)
number of payments
, JavaScript uses the pow() method associated

with the Math object. Table 10-19 shows the general form of the pow() method.

Table 10-19 Math.pow() Method

General form:
Math.pow(number, exponent)

Comment:

where
number
is the value raised to the power of the
exponent
value. The pow() method accepts

variables (X,n), constants (2,3), or both (Sidelength,2).

Math.pow(2,3)

Math.pow(X,n)

Math.pow(Sidelength,2)

Examples:

The return statement in line 71 tells the function to send the results of the

expression back as a fixed decimal value with a length of two. The Number object's

toFixed() method returns a value set to a specific decimal length, as shown in Table 10-20.

Table 10-20 Number.toFixed() Method

General form:
Number.toFixed(digits)

Comment:

where
digits
is the exact number of digits after the decimal point. The number is rounded or

padded with zeros if necessary.

Examples:

Pmt = 234.8932

Pmt.toFixed(3)

Result: 234.893

Amt = 843.6778

Amt.toFixed(2)

Result: 843.68