Skip to main content

Module 9: Numbers & Math

JavaScript numbers and the Math object provide tools for numerical operations, calculations, and mathematical functions.


1. Number Types

// Integers
const int = 42;
const negative = -10;

// Floating-point
const float = 3.14;
const exponential = 1.5e6; // 1500000
const scientific = 2.998e8; // 299800000

// Special values
const infinity = Infinity;
const negInfinity = -Infinity;
const notANumber = NaN;

// BigInt (ES2020) - arbitrary precision
const bigInt = 1234567890123456789012345678901234567890n;
const bigFromString = BigInt('9007199254740991');

2. Number Properties

// Maximum/Minimum values
Number.MAX_VALUE; // 1.7976931348623157e+308
Number.MIN_VALUE; // 5e-324
Number.MAX_SAFE_INTEGER; // 9007199254740991
Number.MIN_SAFE_INTEGER; // -9007199254740991

// Special values
Number.POSITIVE_INFINITY; // Infinity
Number.NEGATIVE_INFINITY; // -Infinity
Number.NaN; // NaN

// Epsilon - smallest difference between two numbers
Number.EPSILON; // 2.220446049250313e-16

3. Number Methods

const num = 42.12345;

// toString() - convert to string
num.toString(); // '42.12345'
(255).toString(16); // 'ff' (hexadecimal)
(8).toString(2); // '1000' (binary)

// toFixed() - fixed decimal places
num.toFixed(2); // '42.12'
(1.005).toFixed(2); // '1.01' (rounded)

// toPrecision() - significant digits
num.toPrecision(4); // '42.12'
(1234.5).toPrecision(3); // '1.23e+3'

// toExponential()
(12345).toExponential(2); // '1.23e+4'

// toLocaleString() - locale-formatted
(1234567.89).toLocaleString('en-US'); // '1,234,567.89'
(1234567.89).toLocaleString('de-DE'); // '1.234.567,89'

// Currency formatting
(1234.56).toLocaleString('en-US', { style: 'currency', currency: 'USD' });\n// '$1,234.56'

4. Number Conversion

// String to Number\nNumber('42'); // 42\nNumber('3.14'); // 3.14\nNumber('42px'); // NaN\nNumber('  42  '); // 42 (trimmed)\n\n// parseInt()\nparseInt('42'); // 42\nparseInt('42.99'); // 42\nparseInt('42px'); // 42\nparseInt('px42'); // NaN\nparseInt('1010', 2); // 10 (binary to decimal)\nparseInt('FF', 16); // 255 (hex to decimal)\n\n// parseFloat()\nparseFloat('3.14'); // 3.14\nparseFloat('3.14px'); // 3.14\n\n// Unary plus\n+'42'; // 42\n+'3.14'; // 3.14\n```\n\n---\n\n## 5. Number Validation\n\n```javascript\n// isNaN() - checks if value is NaN\nisNaN(NaN); // true\nisNaN('hello'); // true (coerces to NaN)\nisNaN(123); // false\n\n// Number.isNaN() - strict check (ES6)\nNumber.isNaN(NaN); // true\nNumber.isNaN('hello'); // false (no coercion)\n\n// isFinite() - checks if finite number\nisFinite(42); // true\nisFinite(Infinity); // false\nisFinite('42'); // true (coercion)\n\n// Number.isFinite() - strict (ES6)\nNumber.isFinite(42); // true\nNumber.isFinite('42'); // false\n\n// Number.isInteger()\nNumber.isInteger(42); // true\nNumber.isInteger(42.5); // false\n\n// Number.isSafeInteger()\nNumber.isSafeInteger(9007199254740991); // true\nNumber.isSafeInteger(9007199254740992); // false\n```\n\n---\n\n## 6. Math Object\n\n### 6.1 Math Properties\n\n```javascript\nMath.PI; // 3.141592653589793\nMath.E; // 2.718281828459045\nMath.LN2; // 0.6931471805599453\nMath.LN10; // 2.302585092994046\nMath.SQRT2; // 1.4142135623730951\n```\n\n### 6.2 Rounding Methods\n\n```javascript\nconst num = 4.7;\n\n// round() - nearest integer\nMath.round(4.7); // 5\nMath.round(4.4); // 4\nMath.round(4.5); // 5\n\n// floor() - round down\nMath.floor(4.9); // 4\nMath.floor(-4.2); // -5\n\n// ceil() - round up\nMath.ceil(4.1); // 5\nMath.ceil(-4.9); // -4\n\n// trunc() - remove decimal\nMath.trunc(4.9); // 4\nMath.trunc(-4.9); // -4\n```\n\n### 6.3 Min & Max\n\n```javascript\nMath.min(1, 5, 3, 9, 2); // 1\nMath.max(1, 5, 3, 9, 2); // 9\n\n// With arrays\nconst numbers = [1, 5, 3, 9, 2];\nMath.min(...numbers); // 1\nMath.max(...numbers); // 9\n```\n\n### 6.4 Random Numbers\n\n```javascript\n// Random between 0 (inclusive) and 1 (exclusive)\nMath.random(); // 0.123456789...\n\n// Random integer between min and max (inclusive)\nfunction randomInt(min, max) {\n  return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n\nrandomInt(1, 10); // Random number from 1 to 10\n\n// Random element from array\nfunction randomElement(arr) {\n  return arr[Math.floor(Math.random() * arr.length)];\n}\n```\n\n### 6.5 Power & Root\n\n```javascript\n// pow() - exponentiation\nMath.pow(2, 3); // 8\nMath.pow(5, 2); // 25\n\n// sqrt() - square root\nMath.sqrt(16); // 4\nMath.sqrt(2); // 1.4142135623730951\n\n// cbrt() - cube root (ES6)\nMath.cbrt(27); // 3\n\n// ** operator (ES2016)\n2 ** 3; // 8\n5 ** 2; // 25\n```\n\n### 6.6 Absolute Value & Sign\n\n```javascript\nMath.abs(-5); // 5\nMath.abs(5); // 5\n\n// sign() - returns -1, 0, or 1\nMath.sign(-5); // -1\nMath.sign(0); // 0\nMath.sign(5); // 1\n```\n\n### 6.7 Trigonometric Functions\n\n```javascript\nMath.sin(Math.PI / 2); // 1\nMath.cos(0); // 1\nMath.tan(Math.PI / 4); // 1\n\nMath.asin(1); // 1.5707963267948966 (π/2)\nMath.acos(1); // 0\nMath.atan(1); // 0.7853981633974483 (π/4)\n\n// atan2() - angle from x-axis to point\nMath.atan2(1, 1); // 0.7853981633974483\n```\n\n### 6.8 Logarithmic Functions\n\n```javascript\nMath.log(Math.E); // 1 (natural log)\nMath.log10(100); // 2 (base 10)\nMath.log2(8); // 3 (base 2)\n\n// exp() - e^x\nMath.exp(1); // 2.718281828459045\n```\n\n---\n\n## 7. Number Precision Issues\n\n```javascript\n// Floating-point precision\n0.1 + 0.2; // 0.30000000000000004 ❌\n\n// Solution 1: toFixed()\n(0.1 + 0.2).toFixed(2); // '0.30'\n\n// Solution 2: Epsilon comparison\nfunction areEqual(a, b) {\n  return Math.abs(a - b) < Number.EPSILON;\n}\n\nareEqual(0.1 + 0.2, 0.3); // true\n\n// Solution 3: Work with integers\nconst result = (10 + 20) / 100; // 0.3\n```\n\n---\n\n## 8. Number Formatting\n\n```javascript\n// Thousands separator\nfunction formatNumber(num) {\n  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');\n}\n\nformatNumber(1234567); // '1,234,567'\n\n// Percentage\nfunction toPercent(num, decimals = 2) {\n  return (num * 100).toFixed(decimals) + '%';\n}\n\ntoPercent(0.1234); // '12.34%'\n\n// File size\nfunction formatBytes(bytes, decimals = 2) {\n  if (bytes === 0) return '0 Bytes';\n  \n  const k = 1024;\n  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];\n  const i = Math.floor(Math.log(bytes) / Math.log(k));\n  \n  return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + ' ' + sizes[i];\n}\n\nformatBytes(1234567); // '1.18 MB'\n```\n\n---\n\n## 9. Common Number Operations\n\n### Clamp Number\n\n```javascript\nfunction clamp(num, min, max) {\n  return Math.min(Math.max(num, min), max);\n}\n\nclamp(15, 0, 10); // 10\nclamp(-5, 0, 10); // 0\nclamp(5, 0, 10); // 5\n```\n\n### Linear Interpolation\n\n```javascript\nfunction lerp(start, end, t) {\n  return start + (end - start) * t;\n}\n\nlerp(0, 100, 0.5); // 50\nlerp(0, 100, 0.25); // 25\n```\n\n### Map Range\n\n```javascript\nfunction mapRange(value, inMin, inMax, outMin, outMax) {\n  return (value - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;\n}\n\nmapRange(5, 0, 10, 0, 100); // 50\nmapRange(75, 0, 100, 0, 1); // 0.75\n```\n\n### Is Between\n\n```javascript\nfunction isBetween(num, min, max) {\n  return num >= min && num <= max;\n}\n\nisBetween(5, 0, 10); // true\n```\n\n---\n\n## 10. Mathematical Calculations\n\n### Average\n\n```javascript\nfunction average(...numbers) {\n  return numbers.reduce((sum, num) => sum + num, 0) / numbers.length;\n}\n\naverage(1, 2, 3, 4, 5); // 3\n```\n\n### Median\n\n```javascript\nfunction median(numbers) {\n  const sorted = [...numbers].sort((a, b) => a - b);\n  const mid = Math.floor(sorted.length / 2);\n  \n  return sorted.length % 2 === 0\n    ? (sorted[mid - 1] + sorted[mid]) / 2\n    : sorted[mid];\n}\n\nmedian([1, 2, 3, 4, 5]); // 3\nmedian([1, 2, 3, 4]); // 2.5\n```\n\n### Standard Deviation\n\n```javascript\nfunction standardDeviation(numbers) {\n  const avg = average(...numbers);\n  const squareDiffs = numbers.map(num => Math.pow(num - avg, 2));\n  const avgSquareDiff = average(...squareDiffs);\n  return Math.sqrt(avgSquareDiff);\n}\n```\n\n### Factorial\n\n```javascript\nfunction factorial(n) {\n  if (n <= 1) return 1;\n  return n * factorial(n - 1);\n}\n\nfactorial(5); // 120\n```\n\n### GCD & LCM\n\n```javascript\n// Greatest Common Divisor\nfunction gcd(a, b) {\n  return b === 0 ? a : gcd(b, a % b);\n}\n\ngcd(48, 18); // 6\n\n// Least Common Multiple\nfunction lcm(a, b) {\n  return Math.abs(a * b) / gcd(a, b);\n}\n\nlcm(4, 6); // 12\n```\n\n---\n\n## Summary\n\nIn this module, you learned:\n- ✅ Number types and special values\n- ✅ Number methods and conversion\n- ✅ Math object and mathematical functions\n- ✅ Random number generation\n- ✅ Handling floating-point precision\n- ✅ Number formatting techniques\n- ✅ Common mathematical operations\n\n:::tip Next Steps\nIn Module 10, you'll learn about **Dates and Time** for working with temporal data.\n:::\n\n---\n\n## Practice Exercises\n\n1. Create a function to calculate compound interest\n2. Implement a random password generator\n3. Build a calculator for basic arithmetic operations\n4. Create a function to convert between temperature scales\n5. Implement a lottery number generator\n6. Write a function to calculate distance between two points\n7. Create a grade calculator with weighted averages\n8. Implement a function to check if a number is prime\n\n---\n\n## Additional Resources\n\n- [MDN: Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)\n- [MDN: Math](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math)\n- [JavaScript.info: Numbers](https://javascript.info/number)