JavaScript Math Object
The JavaScript math object is used to perform mathematical operation.
The Math object includes several mathematical methods.
Below are certain math objects with examples:
1)Math.sqrt(n)
this method returns the square root of the given number.
<!DOCTYPE html>
<html>
<body>
Square Root of 17 is: <span id="p1"></span>
<script>
document.getElementById('p1').innerHTML=Math.sqrt(17);
</script>
</body>
</html>
OUTPUT
Square Root of 17 is: 4.123105625617661
2)Math.random()
This method returns the random number between 0 to 1.
<!DOCTYPE html>
<html>
<body>
<p>This method returns a random number between 0 and 1.</p>
<button onclick="pc()">submit</button>
<p id="ran"></p>
<script>
function pc() {
document.getElementById("ran").innerHTML = Math.random();
}
</script>
</body>
</html>
OUTPUT
0.9021449466235936
3)Math.pow(m,n)
This method returns the m to the power of n i.e. m^n.
<!DOCTYPE html>
<html>
<body>
3 to the power of 4 is: <span id="p3"></span>
<script>
document.getElementById('p3').innerHTML=Math.pow(3,4);
</script>
</body>
</html>
OUTPUT
3 to the power 4 is 81
4)Math.floor(n)
This method returns the lowest integer of a given number. For example 3 for 3.7, 5 for 5.9 etc.
<!DOCTYPE html>
<html>
<body>
Floor of 4.6 is: <span id="p4"></span>
<script>
document.getElementById('p4').innerHTML=Math.floor(4.6);
</script>
</html>
</body>
OUTPUT
Floor of 4.6 is 4
5)Math.ceil(n)
This method returns the largest integer of a number. For example 4 for 3.7, 6 for 5.9 etc.
<!DOCTYPE html>
<html>
<body>
Ceil of 6.8 is: <span id="p5"></span>
<script>
document.getElementById('p5').innerHTML=Math.ceil(6.8);
</script>
</body>
</html>
OUTPUT
Ceil of 6.8 is: 7
0 Comment(s)