JavaScript Math Reference

java dev.to

JavaScript Math Object

The Math Object

The JavaScript Math object allows you to perform mathematical tasks.

The Math object is static.

All methods and properties can be used without creating a Math object first.
Math.PI;
Math Properties (Constants)

The syntax for any Math property is : Math.property.

JavaScript provides 8 mathematical constants that can be accessed as Math properties:
Example

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 
Enter fullscreen mode Exit fullscreen mode

Math Methods

The syntax for Math any methods is : Math.method(number)

Number to Integer

There are 4 common methods to round a number to an integer:


Math.round()
Math.round(x) returns the nearest integer:
Examples

Math.round(4.6);
Math.round(4.5);
Math.round(4.4);
Enter fullscreen mode Exit fullscreen mode

Math.ceil()
Math.ceil(x) returns the value of x rounded up to its nearest integer:
Example

Math.ceil(4.9);
Math.ceil(4.7);
Math.ceil(4.4);
Math.ceil(4.2);
Math.ceil(-4.2);
Enter fullscreen mode Exit fullscreen mode

Math.floor()

Math.floor(x) returns the value of x rounded down to its nearest integer:
Example

Math.floor(4.9);
Math.floor(4.7);
Math.floor(4.4);
Math.floor(4.2);
Math.floor(-4.2);

Enter fullscreen mode Exit fullscreen mode

Math.sqrt()

Math.sqrt(x) returns the square root of x:
Example

Math.sqrt(64);

Enter fullscreen mode Exit fullscreen mode

Reference
https://www.w3schools.com/js/js_math_reference.asp

Source: dev.to

arrow_back Back to Tutorials