Skip to content
Plurafy

Math Operations and Utilities

Mathematical operations and utility functions

Perform complex calculations, generate random numbers with correct distributions, and handle edge cases with special values.

The Math object provides mathematical constants and functions. Understanding numeric precision and rounding is crucial for financial and scientific applications.

// Rounding
Math.round(4.5); // 5
Math.round(4.4); // 4
Math.floor(4.9); // 4
Math.ceil(4.1); // 5
Math.trunc(4.9); // 4
// Absolute value
Math.abs(-42); // 42
// Power and roots
Math.pow(2, 3); // 8
Math.sqrt(16); // 4
Math.cbrt(27); // 3
// Min and max
Math.min(1, 2, 3); // 1
Math.max(1, 2, 3); // 3
Math.min(...array); // Use spread operator
// Random decimal [0, 1)
const random = Math.random();
// Random integer in range
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 10)); // 1-10
// Random element from array
function randomElement(array) {
return array[Math.floor(Math.random() * array.length)];
}
// Shuffle array (Fisher-Yates)
function shuffle(array) {
const arr = [...array];
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
// Convert degrees to radians
function toRadians(degrees) {
return degrees * (Math.PI / 180);
}
// Trigonometric functions
const angle = Math.PI / 4; // 45 degrees
Math.sin(angle); // 0.707...
Math.cos(angle); // 0.707...
Math.tan(angle); // 1
// Inverse trigonometry
Math.asin(0.707); // Angle in radians
Math.acos(0.707);
Math.atan(1); // π/4
// Distance between points
function distance(x1, y1, x2, y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
Math.log(Math.E); // 1 (natural log)
Math.log10(100); // 2
Math.log2(8); // 3
Math.exp(1); // e^1
// Calculate order of magnitude
function orderOfMagnitude(num) {
return Math.floor(Math.log10(Math.abs(num)));
}
// Special values
console.log(Infinity); // Positive infinity
console.log(-Infinity); // Negative infinity
console.log(NaN); // Not a number
// Check for these
Number.isFinite(100); // true
Number.isFinite(Infinity); // false
Number.isNaN(NaN); // true
isNaN('hello'); // true (uses type coercion)
// Floating point precision
0.1 + 0.2; // 0.30000000000000004 (not 0.3!)
function floatEqual(a, b, epsilon = 1e-10) {
return Math.abs(a - b) < epsilon;
}
console.log(floatEqual(0.1 + 0.2, 0.3)); // true
Math.PI; // 3.14159...
Math.E; // 2.71828... (Euler's number)
Math.SQRT2; // √2
Math.LN2; // Natural log of 2
Math.LN10; // Natural log of 10