JS Tutorials
JS Objects
JS Functions
JS Classes
JS Aysnc
Math.PI; // returns 3.141592653589793
Unlike other objects, the Math object has no constructor.
The Math object is static.
All methods and properties can be used without creating a Math object first.
The syntax for any Math property is : Math.property
.
JavaScript provides 8 mathematical constants that can be accessed as Math properties:
Math.E // returns Euler's
number
Math.PI // returns PI
Math.SQRT2 // returns the square root of
2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of
2
Math.LN10 // returns the natural logarithm of
10
Math.LOG2E // returns base 2 logarithm of
E
Math.LOG10E // returns base 10 logarithm of E
The syntax for Math any methods is : Math.method.(number)
There are 4 common methods to round a number to an integer:
Math.round(x) | Returns x rounded to its nearest integer |
Math.ceil(x) | Returns x rounded up to its nearest integer |
Math.floor(x) | Returns x rounded down to its nearest integer |
Math.trunc(x) | Returns the integer part of x |
Math.round(x)
returns the nearest integer:
Math.round(4.9); // returns 5
Math.round(4.7); // returns 5
Math.round(4.4); // returns 4
Math.round(4.2); // returns 4
Math.round(-4.2); // returns -4
Math.ceil(x)
returns the value of x rounded
up to its nearest integer:
Math.ceil(4.9); // returns 5
Math.ceil(4.7); // returns 5
Math.ceil(4.4); // returns 5
Math.ceil(4.2); // returns 5
Math.ceil(-4.2); // returns -4
Math.floor(x)
returns the value of x rounded
down to its nearest integer:
Math.floor(4.9); // returns 4
Math.floor(4.7); // returns 4
Math.floor(4.4); // returns 4
Math.floor(4.2); // returns 4
Math.floor(-4.2); // returns -5
Math.trunc(x)
returns the integer part of x:
Math.trunc(4.9); // returns 4
Math.trunc(4.7); // returns 4
Math.trunc(4.4); // returns 4
Math.trunc(4.2); // returns 4
Math.trunc(-4.2); // returns -4
Math.sign(x)
returns if x is negative, null or positive:
Math.sign(-4); // returns -1
Math.sign(0); // returns 0
Math.sign(4); // returns 1