Mathematical Operations
The Math object provides mathematical constants and functions.
It's a built-in object with properties and methods for mathematical operations.
// Constants
Math.PI; // 3.141592653589793
Math.E; // 2.718281828459045
// Rounding
Math.round(4.7); // 5
Math.ceil(4.1); // 5 (round up)
Math.floor(4.9); // 4 (round down)
Math.trunc(4.9); // 4 (remove decimal)
// Min/Max
Math.max(1, 5, 3); // 5
Math.min(1, 5, 3); // 1
// Power and Square Root
Math.pow(2, 3); // 8 (2³)
Math.sqrt(16); // 4
Math.cbrt(27); // 3 (cube root)
// Random
Math.random(); // Random between 0-1
// Random integer between min and max
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Trigonometry
Math.sin(Math.PI / 2); // 1
Math.cos(0); // 1
Math.tan(Math.PI / 4); // 1
// Absolute value
Math.abs(-5); // 5
- Math.PI - Pi constant
- Math.round() - Round to nearest
- Math.ceil() - Round up
- Math.floor() - Round down
- Math.random() - Random 0-1
- Math.max/min() - Find max/min
- Math.pow() - Exponentiation
- Math.sqrt() - Square root
Try Math Object
<div class="math-demo">
<h3>Math Calculator</h3>
<button onclick="rollDice()">🎲 Roll Dice (1-6)</button>
<button onclick="randomColor()">🎨 Random Color</button>
<button onclick="circleArea()">⭕ Circle Area</button>
<div id="mathOutput"></div>
<hr style="margin: 20px 0;">
<h3>Number Rounder</h3>
<input type="number" id="numberInput" step="0.01" value="4.567">
<button onclick="showRounding()">Show Rounding</button>
<div id="roundOutput"></div>
</div>
Note: Math.random() is great for games, simulations, and random selections!