Math functions in Javascript

By FoxLearn 12/18/2024 4:32:14 AM   22
In JavaScript, you can use built-in math functions to perform various mathematical operations.

Some common examples include functions for rounding, finding square roots, and generating random numbers.

Math.abs() returns the absolute value of a number, which means it converts negative values to positive.

console.log(Math.abs(-5)); // 5
console.log(Math.abs(3));  // 3

Math.round() rounds a number to the nearest integer.

console.log(Math.round(4.7)); // 5
console.log(Math.round(4.3)); // 4

Math.max() returns the largest value among the numbers provided as arguments.

console.log(Math.max(1, 5, 3, 9, 2)); // 9
console.log(Math.max(-1, -5, -3));    // -1

Math.min() returns the smallest value among the numbers provided as arguments.

console.log(Math.min(1, 5, 3, 9, 2)); // 1
console.log(Math.min(-1, -5, -3));    // -5

Math.sqrt() returns the square root of a number.

console.log(Math.sqrt(16));  // 4
console.log(Math.sqrt(25));  // 5
console.log(Math.sqrt(2));   // 1.4142135623730951

Math.random() returns a floating-point, pseudorandom number between 0 (inclusive) and 1 (exclusive).

console.log(Math.random()); // A random number between 0 and 1, e.g., 0.123456789
console.log(Math.random()); // Another random number, e.g., 0.987654321