About Lesson
Number Functions in JavaScript
JavaScript has a number of methods for performing operations on numbers. Here are some common methods:
1. parseInt() and parseFloat():
Parses a string and returns an integer or floating-point number.
JavaScript
let intNumber = "42";
console.log(parseInt(intNumber)); // Output: 42
let floatNumber = "3.14";
console.log(parseFloat(floatNumber)); // Output: 3.14
2. toFixed():
Formats a number to a specified number of decimal places.
JavaScript
let num = 3.14159;
console.log(num.toFixed(2)); // Output: "3.14"
3. toString():
Converts a number to a string.
JavaScript
let num = 42;
console.log(num.toString()); // Output: "42"
4. Math.round():
Rounds a number to the nearest integer.
JavaScript
console.log(Math.round(4.7)); // Output: 5
console.log(Math.round(4.3)); // Output: 4
5. Math.ceil() and Math.floor():
Rounds a number up or down to the nearest integer.
JavaScript
console.log(Math.ceil(4.3)); // Output: 5
console.log(Math.floor(4.7)); // Output: 4
6. Math.min() and Math.max():
Returns the smallest or largest number in a list of arguments.
JavaScript
console.log(Math.min(10, 20, 30)); // Output: 10
console.log(Math.max(10, 20, 30)); // Output: 30
7. Math.random():
Generates a random number between 0 (inclusive) and 1 (exclusive).
JavaScript
console.log(Math.random()); // Output: A random decimal, e.g., 0.345678
8. Math.abs():
Returns the absolute value of a number.
JavaScript
let num = -42;
console.log(Math.abs(num)); // Output: 42
9. Math.pow() and Math.sqrt():
Calculates power and square root.
JavaScript
console.log(Math.pow(2, 3)); // Output: 8 (2^3)
console.log(Math.sqrt(16)); // Output: 4
10. Number.isInteger():
Checks if a value is an integer.
JavaScript
console.log(Number.isInteger(42)); // Output: true
console.log(Number.isInteger(3.14)); // Output: false