The Number and Math Objects

1. The Number object

The Number object is another predefined JavaScript object that offers some useful properties and methods for use with numbers.

Properties of the Number object

- Example:
In the following JS script we create a new property (mult8) to the Number object, this new property multiplies by 8 the value of a variable.
<script type="text/javascript"><!--
var nr = 7;

// creates a new property ( mult8 ) to the Number object
Number.prototype.mul8 = nr*8;

// uses the property "mult8"
document.write(nr.mul8);       // 65
--></script>

Methods of the Number Object


2. The Math object

The Math object is a predefined JavaScript object used for mathematical purposes, it provides constants and functions for more complex operations.
If for example we want to get a random number between 0 and 1, we write:

Properties of the Math object

All of the properties of the Math object contain read-only values, that can be useful in mathematical calculations (They must be written with capital letters). - Example:
<script type="text/javascript"><!--
// find the area of a circle,
var rad = 7.8;           // radius value
var area = Math.PI * (rad * rad);     // gets the area
document.write(area);        // 191.134497044403
--></script>

Methods of the Math Object

The methods of the Math object enable you to perform certain calculations in your scripts.
- Some examples:
1) Alerts the value of the positive square root of 64, which is 8.
<script type="text/javascript"><!--
alert(Math.sqrt(64));         // 8
--></script>

2) Returns the number with the highest value, between 8, 4, 88, 56
<script type="text/javascript"><!--
alert(Math.max(8, 4, 88, 56));       // 88
--></script>

3) The following code would return the value of 4 to the 3rd power
<script type="text/javascript"><!--
alert(Math.pow(4, 3));       // 64
--></script>

- Math.random() only returns numbers between zero and one. If you want to generate a random integer between two integers, you can combine the methods "round()" and "random()", as shown in the following example.
<script type="text/javascript"><!--
// gets an random integer between 1 and 10
var lower = 1;
var higher = 10;
var nr = Math.round(Math.random() * (higher - lower)) + lower;

document.write(nr);
--></script>