Skip to content

JavaScript Number Object

The Number object is the fundamental object for representing numbers in JavaScript. It includes not only the basic numeric type but also provides many useful properties and methods for working with numbers. In this chapter, we'll learn about the JavaScript Number object and its various features and methods.

What is the Number Object

In JavaScript, numbers are a primitive data type, but there also exists a Number object. The Number object provides various properties and methods for handling numbers.

Number Characteristics

  1. Primitive Type: Numbers in JavaScript are primitive types
  2. Object Wrapper: Number object is the wrapper object for numbers
  3. Auto-conversion: Primitive numbers are automatically converted to Number objects
  4. Precision Limits: Follows IEEE 754 standard for double-precision floating-point numbers

Number Basics

Creating Numbers

javascript
// Literal method (recommended)
const num1 = 42;
const num2 = 3.14;
const num3 = -10;

// Number constructor
const num4 = new Number(42);
const num5 = new Number("3.14");
const num6 = new Number(true); // 1
const num7 = new Number(false); // 0
const num8 = new Number(null); // 0
const num9 = new Number(undefined); // NaN

console.log(typeof num1); // "number"
console.log(typeof num4); // "object"
console.log(num1 === num4); // false (different types)
console.log(num1 == num4); // true (same value)

// Number function (type conversion)
const num10 = Number("42");
const num11 = Number("3.14");
const num12 = Number(true);
const num13 = Number(false);
const num14 = Number("hello"); // NaN

console.log(num10); // 42
console.log(num11); // 3.14
console.log(num12); // 1
console.log(num13); // 0
console.log(num14); // NaN

Number Literals

javascript
// Integer literals
const decimal = 42; // Decimal
const binary = 0b101010; // Binary (ES6)
const octal = 0o52; // Octal (ES6)
const hex = 0x2A; // Hexadecimal

console.log(decimal); // 42
console.log(binary); // 42
console.log(octal); // 42
console.log(hex); // 42

// Floating-point literals
const float1 = 3.14;
const float2 = .5; // 0.5
const float3 = 5.; // 5.0
const scientific1 = 1e5; // 100000
const scientific2 = 1.5e-2; // 0.015

// BigInt (ES2020)
const bigInt = 123456789012345678901234567890n;
console.log(bigInt); // 123456789012345678901234567890n

Number Static Properties

javascript
// Basic mathematical constants
console.log(Number.EPSILON); // 2.220446049250313e-16 (smallest difference)
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308 (maximum value)
console.log(Number.MIN_VALUE); // 5e-324 (smallest positive value)
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991 (maximum safe integer)
console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991 (minimum safe integer)
console.log(Number.POSITIVE_INFINITY); // Infinity
console.log(Number.NEGATIVE_INFINITY); // -Infinity
console.log(Number.NaN); // NaN

// Check special values
console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity
console.log(0 / 0); // NaN
console.log(Math.sqrt(-1)); // NaN

// Check if finite
console.log(Number.isFinite(42)); // true
console.log(Number.isFinite(Infinity)); // false
console.log(Number.isFinite(-Infinity)); // false
console.log(Number.isFinite(NaN)); // false
console.log(Number.isFinite("42")); // false (no type coercion)

// Compare with global isFinite
console.log(isFinite("42")); // true (type coercion)
console.log(isFinite(42)); // true

Number Static Methods

Type Checking Methods

javascript
// Number.isNaN() - Check if NaN
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(42)); // false
console.log(Number.isNaN("hello")); // false
console.log(Number.isNaN("NaN")); // false

// Compare with global isNaN
console.log(isNaN(NaN)); // true
console.log(isNaN("hello")); // true (type coercion)
console.log(isNaN("NaN")); // true

// Number.isInteger() - Check if integer
console.log(Number.isInteger(42)); // true
console.log(Number.isInteger(42.0)); // true
console.log(Number.isInteger(42.1)); // false
console.log(Number.isInteger("42")); // false
console.log(Number.isInteger(Infinity)); // false

// Number.isSafeInteger() - Check if safe integer
console.log(Number.isSafeInteger(42)); // true
console.log(Number.isSafeInteger(9007199254740991)); // true
console.log(Number.isSafeInteger(9007199254740992)); // false
console.log(Number.isSafeInteger(1.5)); // false

Type Conversion Methods

javascript
// Number.parseInt() - Parse integer
console.log(Number.parseInt("42")); // 42
console.log(Number.parseInt("42.5")); // 42
console.log(Number.parseInt("42px")); // 42
console.log(Number.parseInt("px42")); // NaN
console.log(Number.parseInt("FF", 16)); // 255

// Number.parseFloat() - Parse float
console.log(Number.parseFloat("3.14")); // 3.14
console.log(Number.parseFloat("3.14px")); // 3.14
console.log(Number.parseFloat("px3.14")); // NaN

// Same as global parseInt/parseFloat
console.log(Number.parseInt === parseInt); // true
console.log(Number.parseFloat === parseFloat); // true

Number Instance Methods

Number Formatting

javascript
const num = 1234.5678;

// toFixed() - Fixed decimal places
console.log(num.toFixed(2)); // "1234.57"
console.log(num.toFixed(0)); // "1235"
console.log(num.toFixed(6)); // "1234.567800"
console.log((1.235).toFixed(2)); // "1.24" (rounding)

// toExponential() - Exponential notation
console.log(num.toExponential()); // "1.2345678e+3"
console.log(num.toExponential(2)); // "1.23e+3"
console.log(num.toExponential(6)); // "1.234568e+3"

// toPrecision() - Specified significant digits
console.log(num.toPrecision()); // "1234.5678"
console.log(num.toPrecision(6)); // "1234.57"
console.log(num.toPrecision(3)); // "1.23e+3"

// toString() - Convert to string
console.log(num.toString()); // "1234.5678"
console.log(num.toString(16)); // "4d2.9197979797979"
console.log(num.toString(2)); // Binary representation
console.log(num.toString(8)); // Octal representation

Number Localization

javascript
const num = 42;

// toLocaleString() - Localized string representation
console.log(num.toLocaleString()); // "42"
console.log((1234567.89).toLocaleString("en-US")); // "1,234,567.89"
console.log((1234567.89).toLocaleString("de-DE")); // "1.234.567,89"

// Using options
console.log((1234567.89).toLocaleString("en-US", {
  style: "currency",
  currency: "USD"
})); // "$1,234,567.89"

console.log((0.1).toLocaleString("en-US", {
  style: "percent"
})); // "10%"

Floating-Point Precision Issues

javascript
// Floating-point precision problem
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false

// Solution 1: Using toFixed()
console.log((0.1 + 0.2).toFixed(1)); // "0.3"
console.log(parseFloat((0.1 + 0.2).toFixed(10))); // 0.3

// Solution 2: Using integer arithmetic
function add(a, b) {
  const factor = 10;
  return (a * factor + b * factor) / factor;
}

console.log(add(0.1, 0.2)); // 0.3

// Solution 3: Using Number.EPSILON
function isEqual(a, b) {
  return Math.abs(a - b) < Number.EPSILON;
}

console.log(isEqual(0.1 + 0.2, 0.3)); // true

// Solution 4: Custom precision comparison
function isEqualWithPrecision(a, b, precision = 10) {
  return Math.abs(a - b) < Math.pow(10, -precision);
}

console.log(isEqualWithPrecision(0.1 + 0.2, 0.3, 10)); // true

BigInt for Large Numbers

javascript
// Issues beyond 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 (precision lost)

// Using BigInt (ES2020)
const bigNum1 = 9007199254740991n;
const bigNum2 = 9007199254740992n;
const bigNum3 = 9007199254740993n;

console.log(bigNum1 + 1n); // 9007199254740992n
console.log(bigNum2 + 1n); // 9007199254740993n
console.log(bigNum3 + 1n); // 9007199254740994n

// BigInt operations
console.log(123456789012345678901234567890n * 2n);
console.log(2n ** 100n);

// BigInt and Number conversion
const bigInt = 42n;
const num = 42;

// BigInt to Number
console.log(Number(bigInt)); // 42

// Number to BigInt (must be integer)
console.log(BigInt(num)); // 42n
// console.log(BigInt(3.14)); // RangeError

Number Utility Functions

javascript
class NumberUtils {
  // Check if number
  static isNumber(value) {
    return typeof value === "number" && !isNaN(value);
  }
  
  // Safe number comparison
  static isEqual(a, b, epsilon = Number.EPSILON) {
    return Math.abs(a - b) < epsilon;
  }
  
  // Check if in range
  static inRange(value, min, max) {
    return value >= min && value <= max;
  }
  
  // Clamp value to range
  static clamp(value, min, max) {
    return Math.min(Math.max(value, min), max);
  }
  
  // Round to specified decimals
  static round(value, decimals = 0) {
    const factor = Math.pow(10, decimals);
    return Math.round(value * factor) / factor;
  }
  
  // Floor to specified decimals
  static floor(value, decimals = 0) {
    const factor = Math.pow(10, decimals);
    return Math.floor(value * factor) / factor;
  }
  
  // Ceil to specified decimals
  static ceil(value, decimals = 0) {
    const factor = Math.pow(10, decimals);
    return Math.ceil(value * factor) / factor;
  }
  
  // Format number
  static format(value, options = {}) {
    const {
      decimals = 2,
      thousandSeparator = ",",
      decimalSeparator = "."
    } = options;
    
    const fixed = value.toFixed(decimals);
    const [integer, decimal] = fixed.split(".");
    
    const formattedInteger = integer.replace(
      /\B(?=(\d{3})+(?!\d))/g,
      thousandSeparator
    );
    
    return decimal 
      ? formattedInteger + decimalSeparator + decimal
      : formattedInteger;
  }
  
  // Generate random number
  static random(min = 0, max = 1) {
    return Math.random() * (max - min) + min;
  }
  
  // Generate random integer
  static randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  
  // Check if prime
  static isPrime(num) {
    if (num <= 1) return false;
    if (num <= 3) return true;
    if (num % 2 === 0 || num % 3 === 0) return false;
    
    for (let i = 5; i * i <= num; i += 6) {
      if (num % i === 0 || num % (i + 2) === 0) {
        return false;
      }
    }
    
    return true;
  }
}

// Usage examples
console.log(NumberUtils.isNumber(42)); // true
console.log(NumberUtils.isEqual(0.1 + 0.2, 0.3)); // true
console.log(NumberUtils.inRange(5, 1, 10)); // true
console.log(NumberUtils.clamp(15, 1, 10)); // 10

console.log(NumberUtils.round(3.14159, 2)); // 3.14
console.log(NumberUtils.floor(3.14159, 2)); // 3.14
console.log(NumberUtils.ceil(3.14159, 2)); // 3.15

console.log(NumberUtils.format(1234567.89)); // "1,234,567.89"
console.log(NumberUtils.random(1, 10)); // Random number between 1 and 10
console.log(NumberUtils.randomInt(1, 10)); // Random integer between 1 and 10
console.log(NumberUtils.isPrime(17)); // true

Intl.NumberFormat for Internationalization

javascript
// Basic usage
const number = 123456.789;

// Default formatting
console.log(new Intl.NumberFormat().format(number)); // "123,456.789"

// Locale-specific formatting
console.log(new Intl.NumberFormat("en-US").format(number)); // "123,456.789"
console.log(new Intl.NumberFormat("de-DE").format(number)); // "123.456,789"

// Currency formatting
console.log(new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD"
}).format(number)); // "$123,456.79"

console.log(new Intl.NumberFormat("de-DE", {
  style: "currency",
  currency: "EUR"
}).format(number)); // "123.456,79 €"

// Percent formatting
console.log(new Intl.NumberFormat("en-US", {
  style: "percent"
}).format(0.1234)); // "12%"

console.log(new Intl.NumberFormat("en-US", {
  style: "percent",
  minimumFractionDigits: 2
}).format(0.1234)); // "12.34%"

// Unit formatting
console.log(new Intl.NumberFormat("en-US", {
  style: "unit",
  unit: "kilometer"
}).format(12.345)); // "12.345 km"

console.log(new Intl.NumberFormat("en-US", {
  style: "unit",
  unit: "kilogram",
  maximumFractionDigits: 2
}).format(12.345)); // "12.35 kg"

// Compact notation
console.log(new Intl.NumberFormat("en-US", {
  notation: "compact"
}).format(123456789)); // "123M"

// Scientific notation
console.log(new Intl.NumberFormat("en-US", {
  notation: "scientific"
}).format(123456789)); // "1.235E8"

// Precision control
console.log(new Intl.NumberFormat("en-US", {
  minimumIntegerDigits: 3,
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
}).format(5)); // "005.00"

Practical Example: Currency Calculator

javascript
class CurrencyCalculator {
  constructor(currency = "USD", locale = "en-US") {
    this.currency = currency;
    this.locale = locale;
    this.formatter = new Intl.NumberFormat(locale, {
      style: "currency",
      currency: currency
    });
  }
  
  // Format currency
  format(amount) {
    return this.formatter.format(amount);
  }
  
  // Addition
  add(...amounts) {
    return amounts.reduce((sum, amount) => sum + amount, 0);
  }
  
  // Subtraction
  subtract(minuend, ...subtrahends) {
    return subtrahends.reduce((result, subtrahend) => result - subtrahend, minuend);
  }
  
  // Apply discount
  applyDiscount(amount, discountPercent) {
    return amount * (1 - discountPercent / 100);
  }
  
  // Apply tax
  applyTax(amount, taxRate) {
    return amount * (1 + taxRate / 100);
  }
  
  // Calculate tip
  calculateTip(amount, tipPercent) {
    return amount * (tipPercent / 100);
  }
  
  // Split bill
  splitBill(totalAmount, numberOfPeople) {
    return totalAmount / numberOfPeople;
  }
  
  // Compound interest
  compoundInterest(principal, rate, time, compoundFrequency = 1) {
    return principal * Math.pow(1 + (rate / 100) / compoundFrequency, compoundFrequency * time);
  }
  
  // Simple interest
  simpleInterest(principal, rate, time) {
    return principal * (rate / 100) * time;
  }
  
  // Loan payment
  loanPayment(principal, annualRate, months) {
    const monthlyRate = (annualRate / 100) / 12;
    return (principal * monthlyRate * Math.pow(1 + monthlyRate, months)) / 
           (Math.pow(1 + monthlyRate, months) - 1);
  }
}

// Usage example
const calculator = new CurrencyCalculator("USD", "en-US");

const price = 100;
const discountedPrice = calculator.applyDiscount(price, 20); // 20% discount
const priceWithTax = calculator.applyTax(discountedPrice, 8); // 8% tax
const tip = calculator.calculateTip(priceWithTax, 15); // 15% tip
const total = calculator.add(priceWithTax, tip);

console.log("Original:", calculator.format(price)); // "$100.00"
console.log("After discount:", calculator.format(discountedPrice)); // "$80.00"
console.log("With tax:", calculator.format(priceWithTax)); // "$86.40"
console.log("Tip:", calculator.format(tip)); // "$12.96"
console.log("Total:", calculator.format(total)); // "$99.36"

// Split bill
const billTotal = 200;
const people = 4;
const perPerson = calculator.splitBill(billTotal, people);
console.log(`Each person pays: ${calculator.format(perPerson)}`); // "$50.00"

// Loan calculation
const loanAmount = 100000;
const annualRate = 5;
const loanTerm = 120; // 10 years (120 months)
const monthlyPayment = calculator.loanPayment(loanAmount, annualRate, loanTerm);
console.log(`Monthly payment: ${calculator.format(monthlyPayment)}`); // "$1,060.66"

Statistical Analysis Tool

javascript
class StatisticalAnalyzer {
  constructor(data) {
    this.data = Array.isArray(data) ? data : [data];
  }
  
  // Basic statistics
  getBasicStats() {
    if (this.data.length === 0) return null;
    
    const sorted = [...this.data].sort((a, b) => a - b);
    const sum = this.data.reduce((acc, val) => acc + val, 0);
    const mean = sum / this.data.length;
    
    return {
      count: this.data.length,
      sum: sum,
      mean: mean,
      median: this.getMedian(sorted),
      min: sorted[0],
      max: sorted[sorted.length - 1],
      range: sorted[sorted.length - 1] - sorted[0]
    };
  }
  
  // Get median
  getMedian(sortedData) {
    const middle = Math.floor(sortedData.length / 2);
    
    if (sortedData.length % 2 === 0) {
      return (sortedData[middle - 1] + sortedData[middle]) / 2;
    }
    
    return sortedData[middle];
  }
  
  // Variance
  getVariance() {
    if (this.data.length === 0) return 0;
    
    const mean = this.getBasicStats().mean;
    const squaredDifferences = this.data.map(num => Math.pow(num - mean, 2));
    return squaredDifferences.reduce((sum, val) => sum + val, 0) / this.data.length;
  }
  
  // Standard deviation
  getStandardDeviation() {
    return Math.sqrt(this.getVariance());
  }
  
  // Percentile
  getPercentile(percentile) {
    if (this.data.length === 0) return null;
    if (percentile < 0 || percentile > 100) return null;
    
    const sorted = [...this.data].sort((a, b) => a - b);
    const index = (percentile / 100) * (sorted.length - 1);
    const lowerIndex = Math.floor(index);
    const upperIndex = Math.ceil(index);
    
    if (lowerIndex === upperIndex) {
      return sorted[lowerIndex];
    }
    
    const weight = index - lowerIndex;
    return sorted[lowerIndex] * (1 - weight) + sorted[upperIndex] * weight;
  }
}

// Usage example
const testData = [1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10, 10, 10, 15, 20, 25, 30];
const analyzer = new StatisticalAnalyzer(testData);

console.log("Basic stats:", analyzer.getBasicStats());
console.log("Variance:", analyzer.getVariance());
console.log("Standard deviation:", analyzer.getStandardDeviation());
console.log("75th percentile:", analyzer.getPercentile(75));

Summary

Key points of the JavaScript Number object:

  1. Basic Concept: Numbers are primitive types, Number is their wrapper object
  2. Creation: Literals, constructor, Number() function
  3. Static Properties: EPSILON, MAX_VALUE, MIN_VALUE, safe integer range, etc.
  4. Static Methods: isFinite(), isNaN(), isInteger(), parseInt(), parseFloat()
  5. Instance Methods: toFixed(), toExponential(), toPrecision(), toString()
  6. Precision Issues: Floating-point precision problems and solutions
  7. BigInt Support: BigInt object for handling large integers
  8. Formatting: Intl.NumberFormat for localized formatting
  9. Math Utilities: Custom utility classes for various math operations
  10. Practical Applications: Currency calculation, statistical analysis, etc.

Mastering the various features and methods of the Number object is essential for accurate numerical calculations and data processing. In the next chapter, we'll learn about the JavaScript Math object.

Content is for learning and research only.