JavaScript Math object allows to do mathematical operations on numbers.
There are various methods available to do mathematical operations
This method creates a random number between 0 an 1
<!DOCTYPE html>
<html>
<body>
Random method generates random number between 0 and 1.<br />
<button onclick="myFunction()">Clict me to generate Random number</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = Math.random();
}
</script>
</body>
</html>
This method returns smallest number from given list
<!DOCTYPE html>
<html>
<body>
Rima is 18 years old.<br />
Rina is 25 years old.<br />
Rita is 20 years old.<br />
<br />
<button onclick="myFunction()">Find Younger</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = 'Rima is younger ' + Math.min(18,20,25);
}
</script>
</body>
</html>
This method returns largest number from given list
<!DOCTYPE html>
<html>
<body>
Rima is 18 years old.<br />
Rina is 25 years old.<br />
Rita is 20 years old.<br />
<br />
<button onclick="myFunction()">Find older</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = 'Rina is oldest from all ' + Math.max(18,20,25);
}
</script>
</body>
</html>
This method returns nearest integer value of given floating number.
<!DOCTYPE html>
<html>
<body>
Math.round() converts number to nearest integer.
<p id="demo"></p>
<script>
document.getElementById('demo').innerHTML = Math.round(45.5);
</script>
</body>
</html>
This method returns nearest largest integer value of given number.
<!DOCTYPE html>
<html>
<body>
Math.ceil() converts number to nearest largest integer.
<p id="demo"></p>
<script>
document.getElementById('demo').innerHTML = Math.round(45.5);
</script>
</body>
</html>
This method returns smallest nearest integer value of given number.
<!DOCTYPE html>
<html>
<body>
Math.floor() converts number to nearest smallest integer.
<p id="demo"></p>
<script>
document.getElementById('demo').innerHTML = Math.floor(45.5);
</script>
</body>
</html>
There are several(total 8) in built Math constants which is accessed using Math object.
<!DOCTYPE html>
<html>
<body>
Math.floor() converts number to nearest smallest integer.
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 'Euler\'s number : ' +
Math.E + "<br> PI value : " +
Math.PI + "<br> Square root of 2 :" +
Math.SQRT2 + "<br> Square root of 1/2 : " +
Math.SQRT1_2 + "<br> Logarithm of 2" +
Math.LN2 + "<br> Logarithm of 10" +
Math.LN10 + "<br>2 logarithm of E" +
Math.LOG2E + "<br>10 logarithm of E" +
Math.LOG10E + "<br>";
</script>
</body>
</html>