JavaScript Numbers

Working with numeric data in JavaScript

🔢 What are JavaScript Numbers?

JavaScript has only one type of number - they can be integers or floating-point numbers. Unlike other languages, JavaScript doesn't distinguish between different number types.


// All of these are numbers in JavaScript
let integer = 42;
let decimal = 3.14159;
let negative = -17;
let scientific = 2.5e6; // 2,500,000

console.log(typeof integer); // Output: number
console.log(typeof decimal); // Output: number
                                    

Number Formats

🔢

Integers

Whole numbers without decimals

let age = 25;
let count = 100;
📊

Decimals

Numbers with decimal points

let price = 19.99;
let pi = 3.14159;
🔬

Scientific Notation

Very large or small numbers

let big = 1.5e6; // 1,500,000
let small = 2.5e-4; // 0.00025
🎯

Special Values

Infinity, -Infinity, and NaN

let inf = Infinity;
let notNum = NaN;

🔹 Number Creation and Conversion

Different ways to create and convert numbers:

// Creating numbers
let num1 = 42;              // Number literal
let num2 = new Number(42);  // Number constructor (not recommended)
let num3 = Number("42");    // Convert string to number
let num4 = parseInt("42");  // Parse integer from string
let num5 = parseFloat("3.14"); // Parse float from string

console.log(num1); // Output: 42
console.log(num3); // Output: 42
console.log(num4); // Output: 42
console.log(num5); // Output: 3.14

// Converting to numbers
let str = "123";
let converted1 = Number(str);    // 123
let converted2 = parseInt(str);  // 123
let converted3 = +str;           // 123 (unary plus operator)

console.log(converted1, converted2, converted3); // Output: 123 123 123

Output:

42

42

42

3.14

123 123 123

🔹 Number Methods

Built-in methods for working with numbers:

let num = 123.456789;

// Convert to string
console.log(num.toString()); // Output: "123.456789"

// Fixed decimal places
console.log(num.toFixed(2)); // Output: "123.46"
console.log(num.toFixed(0)); // Output: "123"

// Precision (total digits)
console.log(num.toPrecision(5)); // Output: "123.46"
console.log(num.toPrecision(3)); // Output: "123"

// Exponential notation
console.log(num.toExponential(2)); // Output: "1.23e+2"

// Value of (for Number objects)
let numObj = new Number(42);
console.log(numObj.valueOf()); // Output: 42

Output:

"123.456789"

"123.46"

"123"

"123.46"

"123"

"1.23e+2"

42

🔹 Number Properties and Constants

JavaScript provides useful number constants:

// Number properties
console.log(Number.MAX_VALUE);        // Largest possible number
console.log(Number.MIN_VALUE);        // Smallest positive number
console.log(Number.MAX_SAFE_INTEGER); // Largest safe integer
console.log(Number.MIN_SAFE_INTEGER); // Smallest safe integer
console.log(Number.POSITIVE_INFINITY); // Positive infinity
console.log(Number.NEGATIVE_INFINITY); // Negative infinity
console.log(Number.NaN);              // Not a Number

// Checking number types
let testNum = 42;
console.log(Number.isInteger(testNum));    // Output: true
console.log(Number.isInteger(42.5));       // Output: false
console.log(Number.isNaN(NaN));            // Output: true
console.log(Number.isNaN(42));             // Output: false
console.log(Number.isFinite(42));          // Output: true
console.log(Number.isFinite(Infinity));    // Output: false

Output:

1.7976931348623157e+308

5e-324

9007199254740991

-9007199254740991

Infinity

-Infinity

NaN

true

false

true

false

true

false

🔹 Math Object

JavaScript's Math object provides mathematical functions:

// Math constants
console.log(Math.PI);    // Output: 3.141592653589793
console.log(Math.E);     // Output: 2.718281828459045

// Rounding methods
console.log(Math.round(4.7));  // Output: 5 (round to nearest)
console.log(Math.ceil(4.1));   // Output: 5 (round up)
console.log(Math.floor(4.9));  // Output: 4 (round down)
console.log(Math.trunc(4.9));  // Output: 4 (remove decimal)

// Min and Max
console.log(Math.min(1, 3, 2));     // Output: 1
console.log(Math.max(1, 3, 2));     // Output: 3

// Power and square root
console.log(Math.pow(2, 3));    // Output: 8 (2^3)
console.log(Math.sqrt(16));     // Output: 4
console.log(Math.abs(-5));      // Output: 5 (absolute value)

// Random numbers
console.log(Math.random());     // Output: random number 0-1
console.log(Math.floor(Math.random() * 10)); // Random 0-9

Output:

3.141592653589793

2.718281828459045

5

5

4

4

1

3

8

4

5

0.7234567891234567 (example)

7 (example)

🔹 Number Precision and Floating Point

Understanding JavaScript number precision:

// Floating point precision issues
console.log(0.1 + 0.2);           // Output: 0.30000000000000004
console.log(0.1 + 0.2 === 0.3);   // Output: false

// Solutions for precision
let sum = 0.1 + 0.2;
console.log(sum.toFixed(1));       // Output: "0.3"
console.log(Math.round(sum * 10) / 10); // Output: 0.3

// Safe integer range
console.log(Number.MAX_SAFE_INTEGER);     // 9007199254740991
console.log(Number.MAX_SAFE_INTEGER + 1); // 9007199254740992
console.log(Number.MAX_SAFE_INTEGER + 2); // 9007199254740992 (same!)

// Checking if number is safe
console.log(Number.isSafeInteger(9007199254740991)); // true
console.log(Number.isSafeInteger(9007199254740992)); // false

Output:

0.30000000000000004

false

"0.3"

0.3

9007199254740991

9007199254740992

9007199254740992

true

false

🔹 Practical Number Examples

Real-world number operations:

Common Number Tasks:

  • Currency: Formatting prices and calculations
  • Percentages: Calculating discounts and taxes
  • Random Numbers: Games and simulations
  • Validation: Checking if input is a valid number
// Currency formatting
let price = 19.99;
let tax = 0.08;
let total = price * (1 + tax);
console.log(`Total: $${total.toFixed(2)}`); // Output: Total: $21.59

// Percentage calculation
let score = 85;
let maxScore = 100;
let percentage = (score / maxScore) * 100;
console.log(`Score: ${percentage}%`); // Output: Score: 85%

// Random number in range
function randomBetween(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomBetween(1, 10)); // Random number 1-10

// Input validation
function isValidNumber(input) {
    return !isNaN(input) && isFinite(input);
}
console.log(isValidNumber("42"));    // Output: true
console.log(isValidNumber("abc"));   // Output: false

🧠 Test Your Knowledge

What does Math.floor(4.9) return?