JavaScript:Math Calculations

Math object
The built-in Math object includes mathematical constants and functions. You do not need to create the Math object before using it.

Math example 1 (js6_01)
Note:Use refresh to see the random number change.

Example js6_01

Math example 2 Currency converter (js6_02)
Notes:


 * ParseFloat: Determines if the first character in the specified string is a number. If it is, it parses the string until it reaches the end of the number, and returns the number as a number, not as a string.
 * this.value is shorthand that says use "this" objects value
 * You need to click "off" the number for the currency to be shown.

Example js6_02

Currency conversion:
An easier solution was made available with JavaScript 1.5

$numin.toFixed(x) e.g.

parseFloat
An issue that arises is when a number is expected in a textBox but the user does not enter one. In this case parseFloat will return Not a Number (NaN) and the arithmetic will not evaluate.

This can be fixed by adding an if statement straight after the number is converted, for example:

This example shows the results of different JavaScript code .

Activity: Simple calculator

 * 1) Create two text boxes (number 1 and Number 2) and four buttons +,*,*,/ plus an Answer text box
 * 2) When a user enters two numbers they can click the appropriate button and the total is placed in the total box