﻿ JavaScript tutorial-Math Object

JavaScript tutorial-Math Object

Math object

JavaScript provides a Math object that comes with useful mathematical methods. In JavaScript you don't need to create a Math object by using new keyword. To call any method of the Math object you simply write Math followed by dot and the method.

abs() method

The first method of Math object that you should know is abs(number) method. It returns the absolute value of the number argument.

Example:

var x=-100;

document.write("The absolute value of x is"+Math.abs(x));

ceil() method

The cell(number) method is used to get the nearest larger integer number of an input decimal number. For example, by using cell() method you will get 3, 5, 8 from 2.9, 4.1, 7.5 respectively.

Example:

var num=12.6;

document.write(Math.ceil(num));

floor() method

You can use the floor(number) method to get the nearest smaller integer number of an input number. For example, you will get 2,3,6 from 2.1, 3.8, 6.5 respectively.

Example:

var num=2.1;

document.write(Math.floor(num));

round() method

The round() method will round up a decimal number if the decimal part is greater than or equal to 5 and round down if the decimal part is less than 5. For example, by using the round(number) method you will get 4, 8, 10 from 3.6, 8.2, 9.5 respectively.

Example:

var num=3.6;

document.write(Math.round(num));

pow() method

The pow(number, power) method is used to raise the power of a number.

Example:

var num=10;

document.write(Math.pow(num,2));//=10*10

random() method

The random() method returns a random decimal number between 0 and 1( excluding 1). If you want to get an random integer you combine the statement with floor() method.

Example:

var rnum=Math.floor(Math.random()*6)+1;//generate random numbers from 1 to 6

document.write(rnum);