Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Math Object

JavaScript Math Object


The Math object is used to perform common arithmetic tasks.


Online example

round()
How to use round().

random()
How to use random() to return a random number between 0 and 1.

max()
How to use max() to return the larger of two given numbers. (Before ECMAScript v3, this method took only two arguments.)

min()
How to use min() to return the smaller of two given numbers. (Before ECMAScript v3, this method took only two arguments.)


Complete Math object reference

We provide Reference manual for the JavaScript Math object, which includes all properties and methods available for arithmetic objects.

The reference contains detailed descriptions of each property and method, along with related examples.


Math object

The Math object is used to perform common arithmetic tasks.

The Math object provides a variety of numeric constants and functions. There is no need to define it before use.

Syntax for using Math properties/methods:

Example

var

x

=

Math

.

PI

;

var

y

=

Math

.

sqrt

(

16

)

;

Note: The Math object does not need to be defined before use.


Numeric values

JavaScript provides 8 numeric values accessible through the Math object:

You can refer to the following usage of JavaScript constants:

Example

Math

.

E

Math

.

PI

Math

.

SQRT2

Math

.

SQRT1_2

Math

.

LN2

Math

.

LN10

Math

.

LOG2E

Math

.

LOG10E


Arithmetic methods

In addition to the numeric values accessible through the Math object, several functions (methods) are available.

The following example uses the Math object's round method to round a number.

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

The output of the code above is:

5

The following example uses the Math object's random() method to return a random number between 0 and 1:

document.write(Math.random());

The output of the code above is:

The following example uses the Math object's floor() method and random() to return a random number between 0 and 11:

document.write(Math.floor(Math.random()*11));

The output of the code above is: