Math functions in Javascript
By Tan Lee Published on Dec 18, 2024 255
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
- How to use sweetalert2
- How to Pass string parameter in an onclick function
- How to format number with commas and decimal in Javascript
- What does 'use strict;' means in Javascript
- How to detect if caps lock is pressed in Javascript
- How to create a Custom Event in Javascript
- How to Check if an Object Has a Property Properly in JavaScript
- How to convert an Uint8Array to string in Javascript
Categories
Popular Posts
Material Lite Admin Template
Nov 14, 2024
HTML Bootstrap 4 Login, Register & Reset Template
Nov 11, 2024
Carpatin Admin Dashboard Template
Nov 15, 2024
Portal HTML Bootstrap
Nov 13, 2024