JavaScript has several built-in methods that you can use to manipulate numbers. Let's go through some of the most commonly used number methods with examples.
1. toString()
This method converts a number to a string.
Example:
let num = 123;
let str = num.toString();
console.log(str); // Output: "123"
2. toFixed()
This method formats a number to a specified number of decimal places.
Example:
let num = 12.34567;
let fixedNum = num.toFixed(2);
console.log(fixedNum); // Output: "12.35"
3. toExponential()
This method converts a number into an exponential (scientific) notation.
Example:
let num = 12345;
let expNum = num.toExponential(2);
console.log(expNum); // Output: "1.23e+4"
4. toPrecision()
This method formats a number to a specified length.
Example:
let num = 123.456;
let preciseNum = num.toPrecision(4);
console.log(preciseNum); // Output: "123.5"
5. Number.isInteger()
This method checks if a value is an integer.
Example:
console.log(Number.isInteger(123)); // Output: true
console.log(Number.isInteger(123.45)); // Output: false
6. Number.parseInt()
This method parses a string and returns an integer.
Example:
let str = "123.45";
let intNum = Number.parseInt(str);
console.log(intNum); // Output: 123
7. Number.parseFloat()
This method parses a string and returns a floating-point number.
Example:
let str = "123.45";
let floatNum = Number.parseFloat(str);
console.log(floatNum); // Output: 123.45
8. isNaN()
This method checks if a value is NaN
(Not-a-Number).
Example:
console.log(isNaN("123")); // Output: false
console.log(isNaN("abc")); // Output: true
9. Number.isFinite()
This method checks if a value is a finite number.
Example:
console.log(Number.isFinite(123)); // Output: true
console.log(Number.isFinite(Infinity)); // Output: false
10. Math.random()
Though not a number method, it’s commonly used with numbers. It returns a random number between 0 (inclusive) and 1 (exclusive).
Example:
let randomNum = Math.random();
console.log(randomNum); // Output: A random number like 0.123456789
These are some of the basic number methods in JavaScript. They help you perform various operations on numbers, like converting them to strings, formatting them, and checking their types.