JavaScript Number is a primitive data type used to store integer,
floating-point, binary, octal, hexadecimal, and exponential values.
Unlike many programming languages, JavaScript uses a single Number
type for both integers and decimal values.
Numbers are used to perform mathematical calculations.
JavaScript supports:
Positive integers
Negative integers
Floating-point numbers
Binary numbers
Octal numbers
Hexadecimal numbers
Exponential numbers
Example:
var n1 = 100;
var n2 = -100;
var n3 = 10.52;
var n4 = -10.52;
Different Types of Numbers
JavaScript supports various numeric formats.
var n1 = 100; // Integer
var n2 = -100; // Negative Integer
var n3 = 10.52; // Float
var n4 = -10.52; // Negative Float
var n5 = 0xfff; // Hexadecimal
var n6 = 256e-5; // Exponential
var n7 = 0o30; // Octal
var n8 = 0b0010001; // Binary
Integer Numbers
Integers are whole numbers without decimal points.
JavaScript can accurately store integers up to 15 digits.
For larger integers, BigInt should be used.
Example:
var n1 = 1234567890123456;
var n2 = 12345678901234569;
var n3 = 9999999999999998;
var n4 = 9999999999999999;
Very large integers may lose precision.
BigInt
BigInt allows storing very large integers accurately.
Simply add n to the end of an integer.
Example:
var int1 = 1234567890123459n;
var int2 = 12345678901234569n;
var int3 = 9999999999999999999n;
BigInt is useful for financial calculations and huge numeric values.
Floating-Point Numbers
Floating-point numbers contain decimal values.
JavaScript keeps approximately 17 decimal digits of precision.
Example:
var f1 = 123456789012345.9;
var f2 = 1234567890123456.9;
var f3 = 1234567890123456.79;
Floating Point Arithmetic
var f1 = 4.1 + 5.2;
var f2 = 10.1 + 10.2;
var f3 = (10.1*100 + 10.2*100)/100;
Floating-point calculations may sometimes produce unexpected results because of binary representation.
Binary, Octal, Hexadecimal & Exponential Numbers
JavaScript supports different number formats.
Binary: Starts with 0b
Octal: Starts with 0o
Hexadecimal: Starts with 0x
Exponential: Uses e notation
Example:
var b = 0b100;
var oct = 0o544;
var hex = 0x123ABC;
var exp = 256e-5;
Number() Function
The Number() function converts other data types into numbers.
Example:
var k = Number('100');
var l = Number('10.5');
var m = Number('0b100');
typeof(k); // number
typeof(l); // number
typeof(m); // number
It is commonly used to convert strings into numeric values.
Number Objects
Using the new keyword creates a Number object.
Example:
var i = new Number('10');
var j = new Number('10.5');
var k = new Number('0b100');