In JavaScript, numbers are used for all kinds of math operations — whether you're counting items, measuring prices, working with decimals, or even using binary or hexadecimal formats
What Is a Number in JavaScript?
In JavaScript, numbers can be:
-
Whole numbers (like
10
) -
Decimals (like
10.5
) -
Binary numbers (like
0b1010
) -
Hexadecimal (like
0xFF
) -
Octal (like
0o10
) -
Exponential (like
1.2e3
)
All numbers in JavaScript use a 64-bit floating-point format, just like in languages such as Java and C#. They follow the IEEE 754 standard.
Number Basics — Examples
Integers in JavaScript
JavaScript can accurately handle integers up to 15 digits. Beyond that, it may round the number.
To work with very large numbers, use BigInt.
BigInt — For Very Large Integers
BigInt lets you store numbers bigger than 15 digits. Just add n
to the end of the number.
Decimal (Floating Point) Numbers
JavaScript can keep decimals accurately up to 17 digits. After that, rounding may happen.
- Note: Floating-point math isn’t always 100% accurate.
To fix that:
Numbers and Strings in Math
If you use math operations (like *
, /
, %
) on strings that contain numbers, JavaScript will convert them to numbers:
But if you use +
, it joins the strings:
Binary, Octal, Hex, Exponential — Special Formats
Type | Format | Example |
---|---|---|
Binary | 0b | 0b1010 |
Octal | 0o | 0o10 |
Hexadecimal | 0x | 0xFF |
Exponential | base + e | 1.5e4 = 15000 |
Convert Other Types to Numbers
Use Number()
to convert strings or other types into numbers:
If you use new Number()
, it returns a number object, not a primitive:
Comparing Numbers
Be careful when comparing numbers, especially objects created with new Number()
.
Number Properties
JavaScript provides built-in properties for number limits:
Property | Description |
---|---|
Number.MAX_VALUE | Largest possible number |
Number.MIN_VALUE | Smallest possible number |
Number.POSITIVE_INFINITY | Infinity |
Number.NEGATIVE_INFINITY | -Infinity |
Number.NaN | Not a Number (e.g., invalid calc) |
Method | What It Does |
---|---|
.toExponential(n) | Shows number in exponential format |
.toFixed(n) | Rounds to n decimal places (returns string) |
.toLocaleString() | Formats based on user’s location |
.toPrecision(n) | Returns number with total n digits |
.toString() | Converts number to string |
.valueOf() | Returns the primitive value from a Number object |
Summary
JavaScript treats all numbers (whether integer or decimal) as the same Number type, and supports many formats:
- Supports: decimal, binary, hex, octal, exponential
- Use
BigInt
for large integers - Math with floating points can be tricky
- Use
Number()
to convert other types - Use number methods to format and display values easily