JavaScript Number Data Type
Number Basics
Numbers in JavaScript are used to represent both integer and floating-point values. JavaScript uses double-precision 64-bit binary format for all numbers.
1// Number declaration examples
2let count = 42;
3let price = 19.99;
4const temperature = -5.5;
5let quantity = 100;
6
7console.log(count); // Output: 42
8console.log(price); // Output: 19.99
9console.log(temperature); // Output: -5.5
10console.log(quantity); // Output: 100
11
12// Different number formats
13let scientific = 2.5e4; // 25000
14let hex = 0xFF; // 255 (hexadecimal)
15let octal = 0o10; // 8 (octal)
16let binary = 0b1010; // 10 (binary)
17
18console.log(scientific); // Output: 25000
19console.log(hex); // Output: 255
20console.log(octal); // Output: 8
21console.log(binary); // Output: 10Number Characteristics
Single Number Type- JavaScript has one number type for both integers and decimals64-bit Floating Point- All numbers are stored as double-precision floating-pointMultiple Formats- Supports decimal, hexadecimal, octal, and binaryScientific Notation- Can represent very large or small numbers using e-notation
Number Declaration Methods
Numbers can be declared in various formats including integers, decimals, and different number systems.
1// Integer numbers
2let age = 25;
3let negative = -15;
4let zero = 0;
5
6// Floating point numbers
7let pi = 3.14159;
8let price = 19.99;
9let small = 0.0001;
10
11// Scientific notation
12let large = 1.5e6; // 1500000
13let smallSci = 2.3e-4; // 0.00023
14
15// Different number systems
16let hex = 0xA; // 10 in hexadecimal
17let hexColor = 0xFF5733; // Color value
18let octal = 0o10; // 8 in octal
19let binary = 0b1101; // 13 in binary
20
21console.log(age); // Output: 25
22console.log(pi); // Output: 3.14159
23console.log(large); // Output: 1500000
24console.log(hex); // Output: 10
25console.log(hexColor); // Output: 16737843
26console.log(octal); // Output: 8
27console.log(binary); // Output: 13
28
29// Number constructor
30let numFromString = Number("42");
31let numFromConstructor = new Number(100); // Not recommended
32
33console.log(numFromString); // Output: 42
34console.log(numFromConstructor); // Output: [Number: 100]Number Formats
Integers- Whole numbers without decimals: 42, -15, 0Floats- Numbers with decimal points: 3.14, -2.5, 0.001Scientific- Large/small numbers: 1e6 (1,000,000), 2e-3 (0.002)Other Bases- Hex (0xFF), octal (0o10), binary (0b1010)
Number Properties and Methods
The Number object provides useful properties and methods for working with numbers, including constants and conversion methods.
1// Number properties (constants)
2console.log(Number.MAX_VALUE); // Output: 1.7976931348623157e+308
3console.log(Number.MIN_VALUE); // Output: 5e-324
4console.log(Number.MAX_SAFE_INTEGER); // Output: 9007199254740991
5console.log(Number.MIN_SAFE_INTEGER); // Output: -9007199254740991
6console.log(Number.POSITIVE_INFINITY); // Output: Infinity
7console.log(Number.NEGATIVE_INFINITY); // Output: -Infinity
8console.log(Number.NaN); // Output: NaN
9
10// Number methods
11let num = 123.45678;
12
13console.log(num.toFixed(2)); // Output: "123.46"
14console.log(num.toPrecision(5)); // Output: "123.46"
15console.log(num.toString()); // Output: "123.45678"
16console.log(num.toString(2)); // Output: "1111011.01110100101111001" (binary)
17console.log(num.toString(16)); // Output: "7b.74bc6a7ef9" (hexadecimal)
18
19// Static Number methods
20console.log(Number.isInteger(42)); // Output: true
21console.log(Number.isInteger(42.5)); // Output: false
22console.log(Number.isFinite(42)); // Output: true
23console.log(Number.isFinite(Infinity)); // Output: false
24console.log(Number.isNaN(NaN)); // Output: true
25console.log(Number.isNaN("text")); // Output: false
26console.log(Number.parseFloat("42.5px")); // Output: 42.5
27console.log(Number.parseInt("42px")); // Output: 42
28
29// Global number functions (older style)
30console.log(parseFloat("3.14")); // Output: 3.14
31console.log(parseInt("101", 2)); // Output: 5 (binary to decimal)Key Number Methods
Formatting- toFixed(), toPrecision() - control decimal places and precisionConversion- toString() - convert to string in different basesValidation- isInteger(), isFinite(), isNaN() - check number propertiesParsing- parseInt(), parseFloat() - extract numbers from strings
Number Operations
JavaScript supports all standard arithmetic operations and provides built-in Math object for advanced mathematical functions.
1// Basic arithmetic operations
2let a = 10, b = 3;
3
4console.log(a + b); // Output: 13 (addition)
5console.log(a - b); // Output: 7 (subtraction)
6console.log(a * b); // Output: 30 (multiplication)
7console.log(a / b); // Output: 3.3333333333333335 (division)
8console.log(a % b); // Output: 1 (modulus/remainder)
9console.log(a ** b); // Output: 1000 (exponentiation)
10
11// Increment and decrement
12let count = 5;
13console.log(count++); // Output: 5 (post-increment)
14console.log(count); // Output: 6
15console.log(++count); // Output: 7 (pre-increment)
16
17// Math object operations
18console.log(Math.PI); // Output: 3.141592653589793
19console.log(Math.sqrt(16)); // Output: 4 (square root)
20console.log(Math.pow(2, 3)); // Output: 8 (power)
21console.log(Math.round(3.7)); // Output: 4 (round)
22console.log(Math.floor(3.7)); // Output: 3 (round down)
23console.log(Math.ceil(3.2)); // Output: 4 (round up)
24console.log(Math.abs(-5)); // Output: 5 (absolute value)
25console.log(Math.max(1, 5, 3)); // Output: 5 (maximum)
26console.log(Math.min(1, 5, 3)); // Output: 1 (minimum)
27console.log(Math.random()); // Output: random number 0-1
28
29// Advanced math functions
30console.log(Math.sin(Math.PI / 2)); // Output: 1 (sine)
31console.log(Math.cos(0)); // Output: 1 (cosine)
32console.log(Math.log(10)); // Output: 2.302585092994046 (natural log)
33console.log(Math.exp(1)); // Output: 2.718281828459045 (exponential)Special Number Cases
JavaScript has special numeric values like Infinity, -Infinity, and NaN that represent mathematical concepts beyond regular numbers.
1// Infinity and -Infinity
2console.log(1 / 0); // Output: Infinity
3console.log(-1 / 0); // Output: -Infinity
4console.log(Number.POSITIVE_INFINITY); // Output: Infinity
5
6console.log(Infinity > 1000); // Output: true
7console.log(-Infinity < -1000); // Output: true
8console.log(Infinity + 1); // Output: Infinity
9console.log(1 / Infinity); // Output: 0
10
11// NaN (Not a Number)
12console.log(0 / 0); // Output: NaN
13console.log("text" * 5); // Output: NaN
14console.log(Math.sqrt(-1)); // Output: NaN
15
16// NaN properties
17console.log(NaN === NaN); // Output: false (special case!)
18console.log(isNaN(NaN)); // Output: true
19console.log(Number.isNaN(NaN)); // Output: true
20console.log(isNaN("hello")); // Output: true (coercion)
21console.log(Number.isNaN("hello")); // Output: false (no coercion)
22
23// Precision issues with floating point
24console.log(0.1 + 0.2); // Output: 0.30000000000000004
25console.log(0.1 + 0.2 === 0.3); // Output: false
26
27// Safe integer range
28console.log(Number.MAX_SAFE_INTEGER); // Output: 9007199254740991
29console.log(Number.MIN_SAFE_INTEGER); // Output: -9007199254740991
30console.log(Number.isSafeInteger(9007199254740991)); // Output: true
31console.log(Number.isSafeInteger(9007199254740992)); // Output: false
32
33// BigInt for larger integers
34const big = 9007199254740993n; // BigInt literal
35console.log(big); // Output: 9007199254740993nNumber Conversion and Parsing
Converting between numbers and strings is common in JavaScript. Understanding the different conversion methods helps avoid unexpected results.
1// String to number conversion
2let str = "42";
3
4console.log(Number(str)); // Output: 42
5console.log(parseInt(str)); // Output: 42
6console.log(parseFloat(str)); // Output: 42
7console.log(+str); // Output: 42 (unary plus)
8
9// Different parsing scenarios
10console.log(parseInt("101", 2)); // Output: 5 (binary to decimal)
11console.log(parseInt("0xFF")); // Output: 255 (hexadecimal)
12console.log(parseInt("42px")); // Output: 42 (ignores non-numeric)
13console.log(parseFloat("3.14.15")); // Output: 3.14 (stops at second dot)
14
15// Number to string conversion
16let num = 42;
17
18console.log(num.toString()); // Output: "42"
19console.log(String(num)); // Output: "42"
20console.log(num + ""); // Output: "42" (implicit)
21console.log(42 .toString(2)); // Output: "101010" (binary)
22console.log(255 .toString(16)); // Output: "ff" (hexadecimal)
23
24// Implicit type coercion
25console.log("5" + 3); // Output: "53" (string concatenation)
26console.log("5" - 3); // Output: 2 (numeric subtraction)
27console.log("5" * "2"); // Output: 10 (numeric multiplication)
28console.log("10" / "2"); // Output: 5 (numeric division)
29
30// Handling invalid conversions
31console.log(Number("hello")); // Output: NaN
32console.log(parseInt("hello")); // Output: NaN
33console.log(+"123abc"); // Output: NaN
34
35// Using Number constructor vs parseInt
36console.log(Number("123.45.67")); // Output: NaN (strict)
37console.log(parseFloat("123.45.67")); // Output: 123.45 (lenient)Number Best Practices
Following best practices when working with numbers helps avoid common pitfalls and ensures accurate mathematical operations.
1// Use const for mathematical constants
2const PI = 3.14159;
3const TAX_RATE = 0.07;
4const MAX_USERS = 1000;
5
6// Avoid floating point precision issues
7// Instead of: 0.1 + 0.2 === 0.3 (false)
8// Use tolerance comparison:
9function areEqual(a, b, tolerance = 0.0001) {
10 return Math.abs(a - b) < tolerance;
11}
12console.log(areEqual(0.1 + 0.2, 0.3)); // Output: true
13
14// Or use integer math when possible
15const totalCents = 10 + 20; // Work in cents instead of dollars
16
17// Use Number() for explicit conversion
18const userInput = "42";
19const numericValue = Number(userInput); // EXPLICIT AND CLEAR
20// const numericValue = +userInput; // LESS CLEAR
21
22// Use parseInt with radix parameter
23console.log(parseInt("10", 10)); // GOOD - explicit base 10
24// console.log(parseInt("10")); // BAD - depends on implementation
25
26// Check for valid numbers
27function isValidNumber(value) {
28 return typeof value === 'number' && !isNaN(value) && isFinite(value);
29}
30
31console.log(isValidNumber(42)); // Output: true
32console.log(isValidNumber(NaN)); // Output: false
33console.log(isValidNumber(Infinity)); // Output: false
34
35// Use Math.floor for integer division
36const result = Math.floor(10 / 3); // Output: 3
37// Instead of: parseInt(10 / 3) which is less clear
38
39// Handle large numbers safely
40const safeMax = Number.MAX_SAFE_INTEGER;
41if (number > safeMax) {
42 // Use BigInt for very large numbers
43 const bigNumber = BigInt(number);
44}
45
46// Use descriptive variable names for numbers
47const itemCount = 5; // GOOD
48const userAge = 25; // GOOD
49const ic = 5; // BAD
50const x = 25; // BAD