JavaScript Math Object Example


The JavaScript Math object can perform mathematical tasks on numbers.

JavaScript Math Object Example

document.writeln("Math.PI = " + Math.PI + "");
//Output : Math.PI = 3.141592653589793

//Math.round(x) returns the value of x rounded to its nearest integer
document.writeln("Math.round(96.521) = " + Math.round(96.521) + "");
//Output : Math.round(96.521) = 97

//Math.pow(x, y) returns the value of x to the power of y
document.writeln("Math.pow(2,10) = " + Math.pow(2,10) + "");
//Output : Math.pow(2,10) = 1024

//Math.sqrt(x) returns the square root of x
document.writeln("Math.sqrt(16) = " + Math.sqrt(16) + "");
//Output : Math.sqrt(16) = 4

//Math.abs(x) returns the absolute (positive) value of x
document.writeln("Math.abs(-17.1) = " + Math.abs(-17.1) + "");
//Output : Math.abs(-17.1) = 17.1

//Math.ceil(x) returns the value of x rounded "up" to its nearest integer
document.writeln("Math.ceil(17.1) = " + Math.ceil(17.1) + "");
//Output : Math.ceil(17.1) = 18

//Math.floor(x) returns the value of x rounded "down" to its nearest integer
document.writeln("Math.floor(17.1) = " + Math.floor(17.1) + "");
//Output : Math.floor(17.1) = 17

//Math.min() can be used to find the lowest value in a list of arguments
document.writeln("Math.min(17,65,-10) = " + Math.min(17,65,-10) + "");
//Output : Math.min(17,65,-10) = -10

//Math.max() can be used to find the highest value in a list of arguments
document.writeln("Math.max(17,65,-10) = " + Math.max(17,65,-10) + "");
//Output : Math.max(17,65,-10) = 65

//Math.random() returns a random number between 0 (inclusive),  and 1 (exclusive)
document.writeln("Math.random() = " + Math.random() + "");

Output from The Program

Math.PI = 3.141592653589793

Math.round(96.521) = 97

Math.pow(2,10) = 1024

Math.sqrt(16) = 4

Math.abs(-17.1) = 17.1

Math.ceil(17.1) = 18

Math.floor(17.1) = 17

Math.min(17,65,-10) = -10

Math.max(17,65,-10) = 65

Math.random() = 0.10506868001523606

JavaScript Math Object

張貼留言

0 留言