JavaScript Math
The JavaScript Math
object provides a wide variety of mathematical functions. These are useful for performing calculations, generating random numbers, and formatting numbers for display purposes.
Syntax
All Math functions are called by the syntax Math.function_name()
. Some of the most commonly used functions are:
Math.random()
: returns a random number between 0 (inclusive) and 1 (exclusive).Math.floor()
: returns the largest integer less than or equal to a given number.Math.ceil()
: returns the smallest integer greater than or equal to a given number.Math.round()
: rounds a given number to the nearest integer.Math.pow()
: returns the base to the exponent power.Math.sqrt()
: returns the square root of a given number.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Math Function Example</title>
</head>
<body>
<!-- Placeholder for displaying the output -->
<p id="output"></p>
<script>
// Math functions example
var num1 = 9;
var num2 = 4;
// Basic arithmetic operations
var sum = num1 + num2;
var difference = num1 - num2;
var product = num1 * num2;
var quotient = num1 / num2;
// Display basic arithmetic results
document.getElementById("output").innerHTML += "Sum: " + sum + "<br>";
document.getElementById("output").innerHTML += "Difference: " + difference + "<br>";
document.getElementById("output").innerHTML += "Product: " + product + "<br>";
document.getElementById("output").innerHTML += "Quotient: " + quotient + "<br>";
// Other Math functions
var squareRoot = Math.sqrt(num1);
var absoluteValue = Math.abs(difference);
var power = Math.pow(num1, 2);
var randomNum = Math.random();
// Display results of other Math functions
document.getElementById("output").innerHTML += "Square Root: " + squareRoot + "<br>";
document.getElementById("output").innerHTML += "Absolute Value: " + absoluteValue + "<br>";
document.getElementById("output").innerHTML += "Power of 2: " + power + "<br>";
document.getElementById("output").innerHTML += "Random Number between 0 and 1: " + randomNum;
</script>
</body>
</html>
Output
The above code will output:
Sum: 13
Difference: 5
Product: 36
Quotient: 2.25
Square Root: 3
Absolute Value: 5
Power of 2: 81
Random Number between 0 and 1: 0.5448967296056955