🔢 Number in JavaScript
🧠 What is a Number?
In JavaScript, all numbers (whether integers or floating point) are represented using the Number type. This is based on the IEEE 754 double-precision 64-bit binary format.
📌 Declaring Numbers
Code Snippet
let age = 25; // Integer
let price = 9.99; // Floating point
let negative = -100; // Negative number
let hex = 0xff; // Hexadecimal
let binary = 0b1010; // Binary
let octal = 0o744; // OctalNote
Unlike some other languages, JavaScript does not distinguish between integers and floats — both are Number type.
📈 Special Number Values
JavaScript provides some special numeric values:
- Infinity – A value greater than any other number.
- -Infinity – A value smaller than any other number.
- NaN – Stands for "Not-a-Number", usually the result of invalid operations.
Code Snippet
console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity
console.log("abc" * 2); // NaN✅ isNaN() and isFinite()
Used to check special values:
Code Snippet
console.log(isNaN(NaN)); // true
console.log(isFinite(123)); // true
console.log(isFinite(Infinity)); // false📏 Number Methods
The Number object provides useful methods for number formatting:
Code Snippet
let num = 123.456;
console.log(num.toFixed(2)); // "123.46"
console.log(num.toPrecision(4)); // "123.5"
console.log(num.toString()); // "123.456"🧮 Math Object
Use the built-in Math object for advanced calculations:
Code Snippet
Math.round(4.7); // 5
Math.floor(4.7); // 4
Math.ceil(4.1); // 5
Math.max(1, 5, 2); // 5
Math.min(1, 5, 2); // 1
Math.random(); // Random number between 0 and 1🔍 Checking for Integer
Code Snippet
Number.isInteger(10); // true
Number.isInteger(10.5); // false📌 BigInt for Larger Integers
For very large integers beyond Number.MAX_SAFE_INTEGER, use BigInt.
Code Snippet
const big = 1234567890123456789012345678901234567890n;
console.log(typeof big); // "bigint"Note
BigInts can't be mixed with regular numbers in arithmetic operations.
🚨 Number Precision Issues
Because of floating-point representation, you may run into precision problems:
Code Snippet
console.log(0.1 + 0.2); // 0.30000000000000004Note
Use rounding or a library like Decimal.js when precision matters.
🧾 Summary
- All numbers in JS are of type Number (except BigInt).
- Special values include Infinity, -Infinity, and NaN.
- Use Math for calculations and Number methods for formatting.
- BigInt is used for arbitrarily large integers.
>>“JavaScript may be loose with types, but its number handling is powerful — once you know the quirks.”