Edit Template
Edit Template

JavaScript Number Object

JavaScript’s Number object provides helpful tools for working with numeric values. Whether you’re converting strings to numbers, formatting decimals, or checking the numeric limits of JavaScript, the Number object has you covered.

Converting Values to Numbers

You can convert strings, booleans, and other types into numbers using the Number() function:

				
					console.log(Number("42.7"));     // 42.7 (string to number)
console.log(Number(false));      // 0 (false becomes 0)
console.log(Number(true));       // 1 (true becomes 1)
console.log(Number("Learn"));    // NaN (Not a Number)

				
			

Parsing Integers and Floats

Use parseInt() for whole numbers and parseFloat() for decimal values:

				
					console.log(parseInt("10.99"));    // 10
console.log(parseFloat("10.99"));  // 10.99

				
			

These methods stop reading when they hit an invalid character:

				
					console.log(parseInt("50px"));   // 50
console.log(parseFloat("5.5kg")); // 5.5

				
			

Number Limits

JavaScript can represent numbers only up to a certain size. You can check these boundaries with Number.MAX_VALUE and Number.MIN_VALUE:

				
					console.log("Max Value:", Number.MAX_VALUE); // ≈ 1.79e+308
console.log("Min Value:", Number.MIN_VALUE); // ≈ 5e-324

				
			

Infinity and NaN

JavaScript supports Infinity, -Infinity, and NaN (Not a Number):

				
					console.log(100 / 0);    // Infinity
console.log(-50 / 0);    // -Infinity
console.log("abc" / 2);  // NaN

				
			

Check if a value is NaN using isNaN():

				
					console.log(isNaN("abc"));    // true
console.log(isNaN("123"));    // false

				
			

Formatting Numbers

The toFixed() method formats numbers with fixed decimal places:

				
					let pi = 3.141592;
console.log(pi.toFixed(2));   // "3.14"
console.log(pi.toFixed(4));   // "3.1416"

				
			

You can also use toPrecision() to format based on total digits:

				
					let value = 123.456;
console.log(value.toPrecision(5)); // "123.46"
console.log(value.toPrecision(2)); // "1.2e+2"

				
			

Conclusion

Here’s what you can do with the JavaScript Number object:

  • Convert values: Number(), parseInt(), parseFloat()

  • Explore limits: Number.MAX_VALUE, Number.MIN_VALUE

  • Detect special values: Infinity, NaN, isNaN()

  • Format output: toFixed(), toPrecision()

Scroll to Top