Number in JavaScript

🧠 Understanding Numbers in JavaScript

In JavaScript, all numeric values (both integers and floating-point numbers) are represented using the Number type. This includes both whole numbers like 42 and decimal values like 3.14.

>>"JavaScript doesn't have separate types for integers and floats — it's all just Number." ✨

📌 Declaring Numbers

Creating Numbers

let age = 30;
let pi = 3.14159;
let negative = -100;
let scientific = 2.5e3;  // 2500

📐 Number Type Details

The Number type in JavaScript uses the 64-bit floating-point format (IEEE 754). This means:

  • ✅ The maximum safe integer is 2^53 - 1 (Number.MAX_SAFE_INTEGER)
  • ✅ The minimum safe integer is -(2^53 - 1) (Number.MIN_SAFE_INTEGER)
  • ✅ Decimal precision may cause rounding errors

Note

💡 Use BigInt if you need very large integers without losing precision.

🧮 Basic Math Operations

Math Operators

let x = 10;
let y = 3;

console.log(x + y);   // 13
console.log(x - y);   // 7
console.log(x * y);   // 30
console.log(x / y);   // 3.333...
console.log(x % y);   // 1 (modulus)
console.log(x ** y);  // 1000 (exponentiation)

🔍 Special Number Values

  • Infinity – Result of division by zero
  • -Infinity – Negative division by zero
  • NaN – "Not-a-Number", usually from invalid operations

Examples of Special Numbers

console.log(1 / 0);        // Infinity
console.log(-1 / 0);       // -Infinity
console.log("abc" * 3);    // NaN

Note

⚠️ NaN is still of type "number" — a well-known JavaScript quirk!

📏 Number Methods & Properties

Common Methods

let num = 123.456;

console.log(num.toFixed(2));      // "123.46"
console.log(num.toString());      // "123.456"
console.log(num.toExponential(1)); // "1.2e+2"
console.log(num.toPrecision(5));  // "123.46"

Some useful static properties:

  • Number.MAX_VALUE – Largest representable number
  • Number.MIN_VALUE – Smallest positive number
  • Number.NaN – Not a number
  • Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY

🧪 Type Conversion

Converting to Number

Number("123");     // 123
parseInt("123.45"); // 123
parseFloat("123.45"); // 123.45

Number("abc");      // NaN
parseInt("abc");    // NaN

Note

📌 Prefer Number() for strict conversion, parseInt() and parseFloat() for parsing strings with potential extra characters.

🔎 Checking for NaN or Finite Values

Validation Functions

Number.isNaN(NaN);             // true
Number.isNaN("abc");          // false
isNaN("abc");                 // true (less reliable)

Number.isFinite(42);          // true
Number.isFinite(Infinity);    // false

📚 Resources to Explore

✅ Summary

  • All numeric values in JavaScript are represented by the Number type
  • Watch out for rounding errors in floating-point math
  • Use toFixed, toPrecision, and toExponential for formatting
  • Use Number.isNaN() and Number.isFinite() to validate numbers safely
>>“Precision is not just a number game — it’s how JavaScript plays with numbers!” 🔍