JavaScript Number Methods
8 April 2025 | Category: JavaScript
JavaScript provides several built-in methods to work with numbers. These methods help you format, convert, and manipulate numbers easily.
Let’s explore the most commonly used number methods in JavaScript.
✅ 1. toString()
Converts a number into a string.
let num = 123;
let str = num.toString();
console.log(str); // Output: "123"
console.log(typeof str); // Output: "string"
✅ 2. toFixed(n)
Returns a string with the number rounded to n
decimal places.
let price = 99.456;
console.log(price.toFixed(2)); // Output: "99.46"
Great for showing prices and controlling decimal output.
✅ 3. toExponential(n)
Returns the number in exponential notation with n
decimals.
let num = 12345;
console.log(num.toExponential(2)); // Output: "1.23e+4"
Used in scientific calculations.
✅ 4. toPrecision(n)
Formats a number to a specified total number of digits (not just decimals).
let num = 9.8765;
console.log(num.toPrecision(3)); // Output: "9.88"
✅ 5. valueOf()
Returns the primitive value of a number. This is rarely used because JavaScript automatically calls it.
let x = 50;
console.log(x.valueOf()); // Output: 50
✅ 6. Number.isInteger()
Checks if a value is an integer.
console.log(Number.isInteger(10)); // true
console.log(Number.isInteger(10.5)); // false
✅ 7. Number.isNaN()
Checks if a value is NaN
(Not a Number).
console.log(Number.isNaN("hello")); // false
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(100 / "apple")); // true
✅ 8. Number.parseInt()
Converts a string to an integer.
let str = "42.9";
console.log(Number.parseInt(str)); // Output: 42
✅ 9. Number.parseFloat()
Converts a string to a floating-point number.
let str = "42.9";
console.log(Number.parseFloat(str)); // Output: 42.9
✅ 10. Number.isFinite()
Checks if a value is a finite number (not Infinity
, -Infinity
, or NaN
).
console.log(Number.isFinite(100)); // true
console.log(Number.isFinite(Infinity)); // false
🧠 Summary Table
Method | Description | Example |
---|---|---|
toString() | Converts number to string | (123).toString() → "123" |
toFixed(n) | Rounds to n decimal places | (5.678).toFixed(2) → "5.68" |
toExponential(n) | Exponential notation with n decimals | (1234).toExponential(1) → "1.2e+3" |
toPrecision(n) | Formats to n digits | (3.14159).toPrecision(3) → "3.14" |
valueOf() | Gets the primitive number value | (100).valueOf() → 100 |
Number.isInteger() | Checks if value is an integer | true / false |
Number.isNaN() | Checks if value is NaN | true / false |
parseInt() | Converts string to integer | "55px" → 55 |
parseFloat() | Converts string to float | "5.5px" → 5.5 |
isFinite() | Checks if value is finite | true / false |