Ad – 728Γ—90
🌱 Beginner

JavaScript Numbers – Integers, Floats, and the Math Object

JavaScript has a single numeric type that handles both integers and floating-point numbers β€” but this design comes with some famous gotchas like 0.1 + 0.2 !== 0.3. This lesson covers how JavaScript numbers work, special values like NaN and Infinity, the full suite of Number methods, the powerful Math object, a brief introduction to BigInt, and how to format numbers for display.

⏱️ 24 min read 🎯 Beginner πŸ“… Updated 2026

The Number Type – 64-bit Float

JavaScript uses the IEEE 754 double-precision 64-bit floating-point standard for all numbers. This means there is no separate int type β€” 42 and 42.0 are the same value.

JavaScript
// All of these are the same type
let integer = 42;
let float   = 3.14;
let negative = -100;
let large   = 1_000_000;     // Numeric separators (ES2021) for readability

console.log(typeof integer);  // "number"
console.log(typeof float);    // "number"
console.log(42 === 42.0);     // true β€” same value!

// Special numeric literals
console.log(0xFF);    // 255  β€” hexadecimal
console.log(0b1010);  // 10   β€” binary
console.log(0o17);    // 15   β€” octal
β–Ά Output
number number true 255 10 15

Floating-Point Precision Issues

The most famous JavaScript number quirk: 0.1 + 0.2 is not exactly 0.3. This is not a JavaScript bug β€” it's a consequence of how IEEE 754 binary floating-point works in all programming languages.

JavaScript
console.log(0.1 + 0.2);          // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3);  // false!

// Solution 1: Use toFixed() for display (returns string)
console.log((0.1 + 0.2).toFixed(2));   // "0.30"

// Solution 2: Compare with an epsilon tolerance
const EPSILON = Number.EPSILON;
console.log(Math.abs(0.1 + 0.2 - 0.3) < EPSILON);  // true

// Solution 3: Use integer math (work in cents, not dollars)
const price1 = 10;  // 10 cents = $0.10
const price2 = 20;  // 20 cents = $0.20
console.log((price1 + price2) / 100 + " dollars");   // "0.3 dollars"
β–Ά Output
0.30000000000000004 false 0.30 true 0.3 dollars
⚠️
Never Use Floats for Money

When building financial applications, always represent monetary values as integers (e.g., cents) or use a dedicated decimal library. 0.1 + 0.2 = 0.30000000000000004 can cause real financial errors if you're not careful.

Ad – 336Γ—280

NaN, Infinity, and -Infinity

JavaScript
// NaN β€” Not a Number (but typeof NaN === "number"!)
console.log(parseInt("hello"));    // NaN
console.log(Math.sqrt(-1));        // NaN
console.log(NaN === NaN);          // false β€” NaN is not equal to itself
console.log(Number.isNaN(NaN));    // true β€” correct way to check
console.log(Number.isNaN("hello")); // false (unlike global isNaN!)

// Infinity
console.log(1 / 0);                // Infinity
console.log(-1 / 0);               // -Infinity
console.log(Infinity + 1);         // Infinity
console.log(Number.isFinite(42));  // true
console.log(Number.isFinite(Infinity)); // false

// Useful constants
console.log(Number.MAX_SAFE_INTEGER);  // 9007199254740991
console.log(Number.MIN_SAFE_INTEGER);  // -9007199254740991
console.log(Number.MAX_VALUE);         // 1.7976931348623157e+308
β–Ά Output
NaN NaN false true false Infinity -Infinity Infinity true false 9007199254740991 -9007199254740991 1.7976931348623157e+308

Number Methods

JavaScript
const n = 123.456;

// toFixed β€” rounds to N decimal places (returns string)
console.log(n.toFixed(2));        // "123.46"
console.log(n.toFixed(0));        // "123"

// toString β€” converts to string, optional radix
console.log(n.toString());        // "123.456"
console.log((255).toString(16));  // "ff" (hexadecimal)
console.log((10).toString(2));    // "1010" (binary)

// Parsing strings to numbers
console.log(parseInt("42px"));      // 42 (stops at non-numeric)
console.log(parseInt("3.9"));       // 3  (truncates decimal)
console.log(parseFloat("3.14abc")); // 3.14
console.log(Number("42"));          // 42
console.log(Number("42.5"));        // 42.5
console.log(Number("42px"));        // NaN β€” strict, no partial parsing
console.log(Number(""));            // 0

// Number.isInteger
console.log(Number.isInteger(42));    // true
console.log(Number.isInteger(42.0));  // true (same value!)
console.log(Number.isInteger(42.5));  // false
β–Ά Output
"123.46" "123" "123.456" "ff" "1010" 42 3 3.14 42 42.5 NaN 0 true true false

The Math Object

The built-in Math object provides mathematical constants and functions. You don't create an instance β€” you use it directly as Math.method().

JavaScript
// Constants
console.log(Math.PI);    // 3.141592653589793
console.log(Math.E);     // 2.718281828459045

// Rounding
console.log(Math.round(4.5));  // 5  β€” rounds to nearest
console.log(Math.floor(4.9));  // 4  β€” rounds down (toward -Infinity)
console.log(Math.ceil(4.1));   // 5  β€” rounds up (toward +Infinity)
console.log(Math.trunc(4.9));  // 4  β€” removes decimal part
console.log(Math.trunc(-4.9)); // -4 (unlike floor which gives -5)

// Min, Max, Absolute value
console.log(Math.min(3, 1, 4, 1, 5, 9));   // 1
console.log(Math.max(3, 1, 4, 1, 5, 9));   // 9
console.log(Math.abs(-42));                 // 42

// Power and roots
console.log(Math.pow(2, 10));   // 1024
console.log(Math.sqrt(144));    // 12
console.log(Math.cbrt(27));     // 3

// Random β€” returns float in [0, 1)
console.log(Math.random());
// Random integer between min (inclusive) and max (exclusive)
const randomInt = (min, max) => Math.floor(Math.random() * (max - min)) + min;
console.log(randomInt(1, 7));   // Random number 1–6 (like a die)
β–Ά Output
3.141592653589793 2.718281828459045 5 4 5 4 -4 1 9 42 1024 12 3 0.7341... (random) 4 (random 1-6)
Math MethodDescriptionExample
Math.round(x)Round to nearest integerMath.round(4.5) β†’ 5
Math.floor(x)Round downMath.floor(4.9) β†’ 4
Math.ceil(x)Round upMath.ceil(4.1) β†’ 5
Math.abs(x)Absolute valueMath.abs(-5) β†’ 5
Math.sqrt(x)Square rootMath.sqrt(9) β†’ 3
Math.pow(x, y)x raised to power yMath.pow(2, 8) β†’ 256
Math.random()Random float [0, 1)Math.random() β†’ 0.742...
Math.log(x)Natural logarithmMath.log(Math.E) β†’ 1

BigInt

BigInt handles integers larger than Number.MAX_SAFE_INTEGER (253–1). Create one by appending n to an integer literal.

JavaScript
const big = 9007199254740993n;
const huge = BigInt("123456789012345678901234567890");

console.log(big + 1n);           // 9007199254740994n
console.log(typeof big);         // "bigint"

// Cannot mix BigInt and Number directly
console.log(big + 1);            // TypeError!
console.log(big + BigInt(1));    // OK: 9007199254740994n
ℹ️
Intl.NumberFormat for Display

Use Intl.NumberFormat to format numbers for display according to locale: new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(1234.5) gives "$1,234.50". This handles locale-specific separators and currency symbols automatically.

πŸ‹οΈ Practical Exercise

  1. Use Math.random() to generate a random integer between 1 and 100 (inclusive).
  2. Use toFixed(2) to format 0.1 + 0.2 for display.
  3. Compute the area of a circle with radius 7 using Math.PI. Round the result to 2 decimal places.
  4. Use parseInt() and parseFloat() to extract numbers from "42px", "3.14em", and "$9.99".
  5. Format the number 1234567.89 as a US dollar currency string using Intl.NumberFormat.

πŸ”₯ Challenge Exercise

Write a function rollDice(sides, count) that simulates rolling count dice each with sides faces. Return an object containing: rolls (array of individual results), total (sum of all rolls), average (rounded to 1 decimal place), min, and max. Test it with rollDice(6, 5).

πŸ“‹ Summary

  • JavaScript uses one 64-bit float type for all numbers β€” no separate int type.
  • Floating-point precision: 0.1 + 0.2 !== 0.3. Use toFixed() for display or integer math for money.
  • NaN is a number type; use Number.isNaN() (not global isNaN()) to check for it.
  • parseInt() extracts leading integer; parseFloat() extracts leading float; Number() requires a valid number string.
  • The Math object provides: round, floor, ceil, abs, sqrt, pow, random, min, max, PI, E.
  • Use BigInt (append n) for integers beyond Number.MAX_SAFE_INTEGER.

Interview Questions

  • Why does 0.1 + 0.2 !== 0.3 in JavaScript?
  • What is the difference between parseInt(), parseFloat(), and Number()?
  • Why should you use Number.isNaN() instead of the global isNaN()?
  • What is Number.MAX_SAFE_INTEGER and why does it matter?
  • How do you generate a random integer between two values in JavaScript?

Frequently Asked Questions

Why does Number("") return 0 instead of NaN? +

This is a JavaScript coercion quirk β€” an empty string is considered "empty" and coerces to 0 rather than NaN. The global isNaN("") also returns false for this reason. Always validate input before converting: check that the string is non-empty and matches a numeric pattern before calling Number().

What is the difference between Math.floor() and Math.trunc()? +

For positive numbers they behave identically. For negative numbers: Math.floor(-4.7) gives -5 (rounds toward negative infinity), while Math.trunc(-4.7) gives -4 (simply removes the decimal, rounding toward zero). Use Math.floor() when you need consistent "round down" behavior.

How do I get a random integer between min and max inclusive? +

Use: Math.floor(Math.random() * (max - min + 1)) + min. For example, to get a random number from 1 to 6 (inclusive): Math.floor(Math.random() * 6) + 1. The + 1 inside the range and the + min at the end are crucial for the bounds to be correct.

Can I use BigInt with the Math object? +

No. Math methods don't support BigInt β€” passing a BigInt to Math.sqrt() or similar will throw a TypeError. BigInt arithmetic uses regular operators (+, -, *, /, %, **) with all operands being BigInt. You must convert to Number first if you need Math operations.

How do I check if a number is an integer? +

Use Number.isInteger(n) β€” it returns true if the value is a number and has no fractional part. Note: Number.isInteger(42.0) returns true because 42.0 === 42 in JavaScript. Avoid n % 1 === 0 β€” it works but is less readable and semantic.