JavaScript Number Object

The Number object in JavaScript is a wrapper object that provides methods for working with numerical values. Numbers in JavaScript are stored as 64-bit floating point values, and the Number object provides a range of methods and properties to handle numeric data.

Key Features of the JavaScript Number Object:

Working with Numbers:

This example demonstrates some basic operations with numbers:

Example


let num1 = 10;
let num2 = 3;
        
console.log(num1 + num2);  // 13 (Addition)
console.log(num1 - num2);  // 7 (Subtraction)
console.log(num1 * num2);  // 30 (Multiplication)
console.log(num1 / num2);  // 3.333... (Division)
console.log(num1 % num2);  // 1 (Modulus)
                    

Output

13
7
30
3.3333333333333335
1

Special Number Values:

JavaScript also defines some special numeric values:

Example


console.log(Number.POSITIVE_INFINITY);  // Infinity
console.log(Number.NEGATIVE_INFINITY);  // -Infinity
console.log(Number.NaN);  // NaN (Not a Number)
                    

Output

Infinity
-Infinity
NaN

Parsing Strings as Numbers:

Use the parseInt() and parseFloat() methods to convert strings to integers and floating-point numbers:

Code Example


let integer = parseInt("123");
let floatNum = parseFloat("123.45");
        
console.log(integer);  // 123
console.log(floatNum); // 123.45
                    

Output

123
123.45

Number Methods:

The Number object also provides several useful methods, such as toFixed() and toExponential(), to format numbers:

Code Example


let num = 1234.5678;
        
console.log(num.toFixed(2));        // 1234.57 (Rounds to 2 decimal places)
console.log(num.toExponential(2));  // 1.23e+3 (Exponential form)
                    

Output

1234.57
1.23e+3

When to Use JavaScript Numbers:

The Number object is essential for any mathematical or numerical calculations, whether working with integers, floating-point values, or performing arithmetic operations. It's commonly used in calculations, data processing, and number formatting.