JavaScript Numbers
8 April 2025 | Category: JavaScript
In JavaScript, numbers are used for everything involving calculations — whether it’s counting, measuring, or even working with decimals. Unlike some other programming languages, JavaScript has only one type of number: it can be integer or floating-point (decimal).
✅ Basic Number Types
let integer = 100; // Integer
let float = 99.99; // Decimal number
Both are treated as number type:
console.log(typeof 100); // Output: "number"
console.log(typeof 99.99); // Output: "number"
📌 Number Operations
You can use basic math operators:
let a = 10;
let b = 3;
console.log(a + b); // Addition (13)
console.log(a - b); // Subtraction (7)
console.log(a * b); // Multiplication (30)
console.log(a / b); // Division (3.333...)
console.log(a % b); // Modulus (1)
🔹 Decimal Precision
JavaScript sometimes gives unexpected results with floating-point math:
console.log(0.1 + 0.2); // Output: 0.30000000000000004 😬
💡 Tip: Use toFixed()
to fix decimal places:
let sum = 0.1 + 0.2;
console.log(sum.toFixed(2)); // Output: "0.30"
🔹 Number Methods
Method | Description |
---|---|
toString() | Converts number to string |
toFixed(n) | Rounds number to n decimal places |
toPrecision(n) | Formats number to n digits total |
parseInt() | Converts string to integer |
parseFloat() | Converts string to float |
Examples:
let num = 123.456;
console.log(num.toString()); // "123.456"
console.log(num.toFixed(1)); // "123.5"
console.log(num.toPrecision(4)); // "123.5"
🔹 Number Constants
console.log(Number.MAX_VALUE); // Largest possible number
console.log(Number.MIN_VALUE); // Smallest possible number
console.log(Number.POSITIVE_INFINITY);
console.log(Number.NEGATIVE_INFINITY);
console.log(Number.NaN); // Not a Number
🔹 Checking for Numbers
Function | Description |
---|---|
isNaN() | Checks if value is Not a Number |
isFinite() | Checks if number is finite |
console.log(isNaN("hello")); // true
console.log(isFinite(100)); // true
console.log(isFinite(Infinity)); // false
🔹 Convert to Numbers
Number("123"); // 123
parseInt("123.45"); // 123
parseFloat("123.45") // 123.45
🔹 Math with Numbers
JavaScript also has a Math
object for advanced calculations:
Math.round(4.7); // 5
Math.floor(4.9); // 4
Math.ceil(4.1); // 5
Math.sqrt(25); // 5
Math.pow(2, 3); // 8
Math.random(); // Random number between 0 and 1
🧠 Summary
Feature | Example | Result |
---|---|---|
Integer | let x = 10; | 10 |
Float | let y = 3.14; | 3.14 |
Addition | x + y | 13.14 |
Convert string | Number("42") | 42 |
Format decimals | num.toFixed(2) | “xx.xx” |