|

JavaScript 50 🧬 Numbers — Number, parseInt, parseFloat

const n1 = 42;
const n2 = 3.14;
const n3 = 0b1010;      // binary
const n4 = 0o777;       // octal
const n5 = 0xFF;        // hex
const n6 = 1_000_000;   // numeric separator

console.log(Number('42'));
console.log(Number('3.14'));
console.log(Number(''));

console.log(parseInt('42'));
console.log(parseInt('42px'));
console.log(parseInt('FF', 16));

console.log(parseFloat('3.14'));
console.log(parseFloat('3.14abc'));

console.log(Number.isInteger(42));
console.log(Number.isInteger(3.14));
console.log(Number.isNaN(NaN));
console.log(Number.isFinite(42));
console.log(Number.isFinite(Infinity));

console.log(Number.MAX_SAFE_INTEGER);
console.log(Number.MIN_SAFE_INTEGER);
console.log(Number.MAX_VALUE);
console.log(Number.EPSILON);

console.log((3.14159).toFixed(2));
console.log((255).toString(16));
console.log((3.14).toPrecision(2));
console.log((1234.5678).toExponential(2));

JavaScript has one number type — a 64-bit floating-point value. There’s no separate integer type (except BigInt). Understanding how it behaves — including its limits and quirks — is essential for writing correct numeric code.

Key point: All JavaScript numbers are IEEE 754 double-precision floating-point. This means integers up to 2^53 are exact, but floating-point arithmetic can produce surprising results like 0.1 + 0.2 !== 0.3. Know the workarounds and when to use BigInt.


a – Number basics

Numbers in JavaScript are doubles — always. Whether you write 42 or 3.14, the type is the same.

Number literals:

LiteralExampleValue
Decimal4242
Float3.143.14
Binary0b101010
Octal0o777511
Hex0xFF255
Exponential1e31000
Separator1_000_0001000000
const dec = 42;
const float = 3.14;
const bin = 0b1010;       // 10
const oct = 0o777;        // 511
const hex = 0xFF;         // 255
const exp = 1e3;          // 1000
const sep = 1_000_000;    // 1000000

console.log(bin, oct, hex, exp, sep);
// [ 10 511 255 1000 1000000 ]

Special numeric values:

ValueMeaning
NaNNot a Number
InfinityPositive infinity
-InfinityNegative infinity
-0Negative zero
Number.MAX_SAFE_INTEGER2^53 – 1
Number.MIN_SAFE_INTEGER-(2^53 – 1)
Number.MAX_VALUELargest representable
Number.MIN_VALUESmallest positive
Number.EPSILONSmallest difference
console.log(1 / 0);
// [ Infinity ]

console.log(-1 / 0);
// [ -Infinity ]

console.log(0 / 0);
// [ NaN ]

console.log(Number.MAX_SAFE_INTEGER);
// [ 9007199254740991 ]

console.log(Number.MIN_SAFE_INTEGER);
// [ -9007199254740991 ]

console.log(Number.MAX_VALUE);
// [ 1.7976931348623157e+308 ]

console.log(Number.EPSILON);
// [ 2.220446049250313e-16 ]

The floating-point reality:

console.log(0.1 + 0.2);
// [ 0.30000000000000004 ]

console.log(0.1 + 0.2 === 0.3);
// [ false ]

This isn’t a JavaScript bug — it’s how IEEE 754 works. Many decimal fractions can’t be represented exactly in binary.

Comparing floats — use Number.EPSILON:

function almostEqual(a, b, epsilon = Number.EPSILON) {
  return Math.abs(a - b) < epsilon;
}

console.log(almostEqual(0.1 + 0.2, 0.3));
// [ true ]

Safe integers:

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

console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER));
// [ true ]

console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1));
// [ false ]

Beyond 2^53 – 1, integers lose precision. Use BigInt for larger values.

typeof numbers:

console.log(typeof 42);
// [ 'number' ]

console.log(typeof NaN);
// [ 'number' ]  ← yes, NaN is a number

console.log(typeof Infinity);
// [ 'number' ]

b – Number methods and properties

The Number global provides static methods for checking and constants.

Static properties:

PropertyValue
Number.MAX_SAFE_INTEGER2^53 – 1
Number.MIN_SAFE_INTEGER-(2^53 – 1)
Number.MAX_VALUE~1.79e+308
Number.MIN_VALUE~5e-324
Number.EPSILON~2.22e-16
Number.POSITIVE_INFINITYInfinity
Number.NEGATIVE_INFINITY-Infinity
Number.NaNNaN

Static methods:

MethodPurpose
Number.isInteger(x)Is integer?
Number.isFinite(x)Is finite?
Number.isNaN(x)Is NaN?
Number.isSafeInteger(x)Safe integer?
Number.parseFloat(x)Same as global parseFloat
Number.parseInt(x, radix)Same as global parseInt

Number.isInteger:

console.log(Number.isInteger(42));
// [ true ]

console.log(Number.isInteger(3.14));
// [ false ]

console.log(Number.isInteger(42.0));
// [ true ]  ← 42.0 is the same as 42

console.log(Number.isInteger('42'));
// [ false ]  ← doesn't coerce

Number.isFinite:

console.log(Number.isFinite(42));
// [ true ]

console.log(Number.isFinite(Infinity));
// [ false ]

console.log(Number.isFinite(NaN));
// [ false ]

console.log(Number.isFinite('42'));
// [ false ]  ← doesn't coerce

Number.isNaN:

console.log(Number.isNaN(NaN));
// [ true ]

console.log(Number.isNaN('hello'));
// [ false ]

console.log(Number.isNaN(42));
// [ false ]

// vs global isNaN — which coerces
console.log(isNaN('hello'));
// [ true ]  ← coerces to number, then checks

Always use Number.isNaN — the global isNaN coerces its argument and gives surprising results.

Number.isSafeInteger:

console.log(Number.isSafeInteger(42));
// [ true ]

console.log(Number.isSafeInteger(2 ** 53));
// [ false ]

Instance methods — on number values:

MethodReturns
num.toString(base)String in base
num.toFixed(n)Fixed-point string
num.toPrecision(n)N significant digits
num.toExponential(n)Exponential notation
num.valueOf()Primitive value

toString(base) — convert to string in a base:

console.log((255).toString(16));
// [ 'ff' ]

console.log((255).toString(2));
// [ '11111111' ]

console.log((255).toString(8));
// [ '377' ]

console.log((255).toString(10));
// [ '255' ]

toFixed(n) — fixed decimal places:

console.log((3.14159).toFixed(2));
// [ '3.14' ]

console.log((3.14159).toFixed(4));
// [ '3.1416' ]

console.log((42).toFixed(2));
// [ '42.00' ]

Returns a string, not a number.

toPrecision(n) — significant digits:

console.log((3.14159).toPrecision(3));
// [ '3.14' ]

console.log((1234.5).toPrecision(2));
// [ '1.2e+3' ]

console.log((0.000123).toPrecision(2));
// [ '0.00012' ]

toExponential(n) — scientific notation:

console.log((123456).toExponential(2));
// [ '1.23e+5' ]

console.log((0.000123).toExponential(2));
// [ '1.23e-4' ]

Number coercion — Number():

console.log(Number('42'));
// [ 42 ]

console.log(Number('3.14'));
// [ 3.14 ]

console.log(Number(''));
// [ 0 ]

console.log(Number('  42  '));
// [ 42 ]  ← trims whitespace

console.log(Number('hello'));
// [ NaN ]

console.log(Number(true));
// [ 1 ]

console.log(Number(false));
// [ 0 ]

console.log(Number(null));
// [ 0 ]

console.log(Number(undefined));
// [ NaN ]
InputNumber()
'42'42
'3.14'3.14
''0
' 42 '42
'42px'NaN
'0x1A'26
true1
false0
null0
undefinedNaN
[]0
[5]5
[1,2]NaN
{}NaN

parseInt vs parseFloat vs Number:

FunctionPurpose'42px''3.14abc''0xFF'
Number()Strict coercionNaNNaN255
parseInt()Parse int from start423255
parseFloat()Parse float from start423.140

parseInt — parse an integer:

console.log(parseInt('42'));
// [ 42 ]

console.log(parseInt('42px'));
// [ 42 ]  ← stops at first non-digit

console.log(parseInt('3.14'));
// [ 3 ]  ← stops at '.'

console.log(parseInt('FF', 16));
// [ 255 ]

console.log(parseInt('1010', 2));
// [ 10 ]

console.log(parseInt('hello'));
// [ NaN ]

Always pass a radix — the default (10) isn’t guaranteed on all engines:

parseInt('08');       // ⚠️  might be 8 or NaN in old engines
parseInt('08', 10);   // ✅ always 8

Radix examples:

parseInt('10', 2);    // 2
parseInt('10', 8);    // 8
parseInt('10', 10);   // 10
parseInt('10', 16);   // 16
parseInt('FF', 16);   // 255
parseInt('Z', 36);    // 35

parseFloat — parse a float:

console.log(parseFloat('3.14'));
// [ 3.14 ]

console.log(parseFloat('3.14abc'));
// [ 3.14 ]

console.log(parseFloat('42'));
// [ 42 ]

console.log(parseFloat('1e3'));
// [ 1000 ]

console.log(parseFloat('.5'));
// [ 0.5 ]

console.log(parseFloat('hello'));
// [ NaN ]

Rounding numbers:

Math handles rounding — toFixed just formats:

MethodEffect
Math.round(x)Nearest integer (half up)
Math.floor(x)Down
Math.ceil(x)Up
Math.trunc(x)Drop decimal
.toFixed(n)Format to n decimals (string)
console.log(Math.round(3.5));
// [ 4 ]

console.log(Math.floor(3.9));
// [ 3 ]

console.log(Math.ceil(3.1));
// [ 4 ]

console.log(Math.trunc(3.9));
// [ 3 ]

Checking for numbers:

function isNumber(x) {
  return typeof x === 'number' && !Number.isNaN(x);
}

console.log(isNumber(42));
// [ true ]

console.log(isNumber(NaN));
// [ false ]

console.log(isNumber('42'));
// [ false ]

c – Common number patterns

These patterns come up constantly in real code.

Pattern 1 — Round to n decimals:

function round(n, places) {
  const factor = 10 ** places;
  return Math.round(n * factor) / factor;
}

console.log(round(3.14159, 2));
// [ 3.14 ]

console.log(round(3.14159, 4));
// [ 3.1416 ]

Pattern 2 — Format as currency:

const fmt = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD'
});

console.log(fmt.format(1234.5));
// [ '$1,234.50' ]

Pattern 3 — Format with thousands separator:

const fmt = new Intl.NumberFormat('en-US');
console.log(fmt.format(1234567));
// [ '1,234,567' ]

Pattern 4 — Format as percentage:

const fmt = new Intl.NumberFormat('en-US', { style: 'percent' });
console.log(fmt.format(0.25));
// [ '25%' ]

Pattern 5 — Clamp between min and max:

function clamp(n, min, max) {
  return Math.min(Math.max(n, min), max);
}

console.log(clamp(5, 0, 10));
// [ 5 ]

console.log(clamp(-5, 0, 10));
// [ 0 ]

console.log(clamp(15, 0, 10));
// [ 10 ]

Pattern 6 — Random integer in range:

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(randomInt(1, 10));
// [ 7 ] (varies)

Pattern 7 — Check if number is integer:

console.log(Number.isInteger(42));
// [ true ]

console.log(Number.isInteger(42.0));
// [ true ]

console.log(Number.isInteger(42.5));
// [ false ]

Pattern 8 — Check if number is even:

function isEven(n) {
  return Number.isInteger(n) && n % 2 === 0;
}

console.log(isEven(4));
// [ true ]

console.log(isEven(5));
// [ false ]

Pattern 9 — Absolute value:

console.log(Math.abs(-42));
// [ 42 ]

Pattern 10 — Safe integer parse:

function safeParseInt(str, radix = 10) {
  const n = parseInt(str, radix);
  return Number.isNaN(n) ? null : n;
}

console.log(safeParseInt('42'));
// [ 42 ]

console.log(safeParseInt('hello'));
// [ null ]

Pattern 11 — Sum with precision:

function sum(...nums) {
  return Number(nums.reduce((a, b) => a + b, 0).toFixed(10));
}

console.log(sum(0.1, 0.2));
// [ 0.3 ]

Pattern 12 — Parse user input:

function parseUserNumber(input) {
  const n = Number(input.trim());
  if (!Number.isFinite(n)) {
    throw new Error('Not a valid number');
  }
  return n;
}

Pattern 13 — Convert string to number safely:

function toNumber(str) {
  if (typeof str !== 'string') return NaN;
  const n = Number(str);
  return n;
}

console.log(toNumber('42'));
// [ 42 ]

console.log(toNumber('3.14'));
// [ 3.14 ]

console.log(toNumber('abc'));
// [ NaN ]

Pattern 14 — Format bytes:

function formatBytes(bytes) {
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let i = 0;
  while (bytes >= 1024 && i < units.length - 1) {
    bytes /= 1024;
    i++;
  }
  return `${bytes.toFixed(2)} ${units[i]}`;
}

console.log(formatBytes(1536));
// [ '1.50 KB' ]

console.log(formatBytes(1048576));
// [ '1.00 MB' ]

Pattern 15 — Hex / binary / octal conversions:

function toHex(n) { return '0x' + n.toString(16).toUpperCase(); }
function toBin(n) { return '0b' + n.toString(2); }
function toOct(n) { return '0o' + n.toString(8); }

console.log(toHex(255));
// [ '0xFF' ]

console.log(toBin(10));
// [ '0b1010' ]

console.log(toOct(8));
// [ '0o10' ]

Pattern 16 — Decimal precision with toFixed:

const price = 19.999;
console.log(price.toFixed(2));
// [ '20.00' ]

// Convert back to number
console.log(Number(price.toFixed(2)));
// [ 20 ]

Pattern 17 — Truncate without rounding:

console.log(Math.trunc(3.99));
// [ 3 ]

console.log(Math.trunc(-3.99));
// [ -3 ]

Pattern 18 — Compare floats with epsilon:

function almostEqual(a, b, eps = 1e-9) {
  return Math.abs(a - b) < eps;
}

console.log(almostEqual(0.1 + 0.2, 0.3));
// [ true ]

Pattern 19 — BigInt for very large integers:

const big = 9007199254740993n;   // note the 'n'
console.log(big);
// [ 9007199254740993n ]

console.log(typeof big);
// [ 'bigint' ]

console.log(big + 1n);
// [ 9007199254740994n ]

Pattern 20 — Intl.NumberFormat for locale-aware formatting:

const de = new Intl.NumberFormat('de-DE');
const us = new Intl.NumberFormat('en-US');

console.log(de.format(1234.5));
// [ '1.234,5' ]

console.log(us.format(1234.5));
// [ '1,234.5' ]

Complete Example Session

// ============================================
// PART 1: NUMBER LITERALS
// ============================================

console.log(42);
// [ 42 ]

console.log(3.14);
// [ 3.14 ]

console.log(0b1010);
// [ 10 ]

console.log(0o777);
// [ 511 ]

console.log(0xFF);
// [ 255 ]

console.log(1e3);
// [ 1000 ]

console.log(1_000_000);
// [ 1000000 ]

// ============================================
// PART 2: SPECIAL VALUES
// ============================================

console.log(1 / 0);
// [ Infinity ]

console.log(-1 / 0);
// [ -Infinity ]

console.log(0 / 0);
// [ NaN ]

console.log(Number.MAX_SAFE_INTEGER);
// [ 9007199254740991 ]

console.log(Number.EPSILON);
// [ 2.220446049250313e-16 ]

// ============================================
// PART 3: FLOATING-POINT QUIRK
// ============================================

console.log(0.1 + 0.2);
// [ 0.30000000000000004 ]

console.log(0.1 + 0.2 === 0.3);
// [ false ]

// ============================================
// PART 4: NUMBER COERCION
// ============================================

console.log(Number('42'));
// [ 42 ]

console.log(Number('3.14'));
// [ 3.14 ]

console.log(Number(''));
// [ 0 ]

console.log(Number('hello'));
// [ NaN ]

console.log(Number(true));
// [ 1 ]

console.log(Number(null));
// [ 0 ]

console.log(Number(undefined));
// [ NaN ]

// ============================================
// PART 5: PARSEINT
// ============================================

console.log(parseInt('42'));
// [ 42 ]

console.log(parseInt('42px'));
// [ 42 ]

console.log(parseInt('3.14'));
// [ 3 ]

console.log(parseInt('FF', 16));
// [ 255 ]

console.log(parseInt('1010', 2));
// [ 10 ]

console.log(parseInt('hello'));
// [ NaN ]

// ============================================
// PART 6: PARSEFLOAT
// ============================================

console.log(parseFloat('3.14'));
// [ 3.14 ]

console.log(parseFloat('3.14abc'));
// [ 3.14 ]

console.log(parseFloat('1e3'));
// [ 1000 ]

console.log(parseFloat('hello'));
// [ NaN ]

// ============================================
// PART 7: STATIC CHECKS
// ============================================

console.log(Number.isInteger(42));
// [ true ]

console.log(Number.isInteger(42.5));
// [ false ]

console.log(Number.isFinite(42));
// [ true ]

console.log(Number.isFinite(Infinity));
// [ false ]

console.log(Number.isNaN(NaN));
// [ true ]

console.log(Number.isSafeInteger(2 ** 53));
// [ false ]

// ============================================
// PART 8: TOSTRING
// ============================================

console.log((255).toString(16));
// [ 'ff' ]

console.log((255).toString(2));
// [ '11111111' ]

console.log((255).toString(8));
// [ '377' ]

// ============================================
// PART 9: TOFIXED
// ============================================

console.log((3.14159).toFixed(2));
// [ '3.14' ]

console.log((42).toFixed(2));
// [ '42.00' ]

// ============================================
// PART 10: TOPRECISION
// ============================================

console.log((3.14159).toPrecision(3));
// [ '3.14' ]

console.log((1234.5).toPrecision(2));
// [ '1.2e+3' ]

// ============================================
// PART 11: TOEXPONENTIAL
// ============================================

console.log((123456).toExponential(2));
// [ '1.23e+5' ]

// ============================================
// PART 12: MATH ROUNDING
// ============================================

console.log(Math.round(3.5));
// [ 4 ]

console.log(Math.floor(3.9));
// [ 3 ]

console.log(Math.ceil(3.1));
// [ 4 ]

console.log(Math.trunc(3.9));
// [ 3 ]

// ============================================
// PART 13: ALMOST EQUAL
// ============================================

function almostEqual(a, b, eps = Number.EPSILON) {
  return Math.abs(a - b) < eps;
}

console.log(almostEqual(0.1 + 0.2, 0.3));
// [ true ]

// ============================================
// PART 14: ROUND TO DECIMALS
// ============================================

function round(n, places) {
  const factor = 10 ** places;
  return Math.round(n * factor) / factor;
}

console.log(round(3.14159, 2));
// [ 3.14 ]

// ============================================
// PART 15: CLAMP
// ============================================

function clamp(n, min, max) {
  return Math.min(Math.max(n, min), max);
}

console.log(clamp(15, 0, 10));
// [ 10 ]

// ============================================
// PART 16: RANDOM INT
// ============================================

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(typeof randomInt(1, 10));
// [ 'number' ]

// ============================================
// PART 17: CURRENCY FORMAT
// ============================================

const currency = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD'
});

console.log(currency.format(1234.5));
// [ '$1,234.50' ]

// ============================================
// PART 18: THOUSANDS SEPARATOR
// ============================================

const sep = new Intl.NumberFormat('en-US');
console.log(sep.format(1234567));
// [ '1,234,567' ]

// ============================================
// PART 19: BIGINT
// ============================================

const big = 9007199254740993n;
console.log(big);
// [ 9007199254740993n ]

console.log(typeof big);
// [ 'bigint' ]

// ============================================
// PART 20: FULL SCRIPT
// ============================================

const n1_50 = 42;
const n2_50 = 3.14;
const n3_50 = 0b1010;
const n4_50 = 0o777;
const n5_50 = 0xFF;
const n6_50 = 1_000_000;

console.log(Number('42'));
console.log(Number('3.14'));
console.log(Number(''));

console.log(parseInt('42'));
console.log(parseInt('42px'));
console.log(parseInt('FF', 16));

console.log(parseFloat('3.14'));
console.log(parseFloat('3.14abc'));

console.log(Number.isInteger(42));
console.log(Number.isInteger(3.14));
console.log(Number.isNaN(NaN));
console.log(Number.isFinite(42));
console.log(Number.isFinite(Infinity));

console.log(Number.MAX_SAFE_INTEGER);
console.log(Number.MIN_SAFE_INTEGER);
console.log(Number.MAX_VALUE);
console.log(Number.EPSILON);

console.log((3.14159).toFixed(2));
console.log((255).toString(16));
console.log((3.14).toPrecision(2));
console.log((1234.5678).toExponential(2));

Quick Reference

Number Literals

LiteralExampleValue
Decimal4242
Float3.143.14
Binary0b101010
Octal0o777511
Hex0xFF255
Exponential1e31000
Separator1_000_0001000000

Special Values

ValueMeaning
NaNNot a Number
InfinityPositive infinity
-InfinityNegative infinity
-0Negative zero

Number Static Properties

PropertyValue
MAX_SAFE_INTEGER2^53 – 1
MIN_SAFE_INTEGER-(2^53 – 1)
MAX_VALUE~1.79e+308
MIN_VALUE~5e-324
EPSILON~2.22e-16

Number Static Methods

MethodPurpose
isInteger(x)Integer?
isFinite(x)Finite?
isNaN(x)NaN?
isSafeInteger(x)Safe?
parseInt(x, r)Same as global
parseFloat(x)Same as global

Instance Methods

MethodReturns
toString(base)String in base
toFixed(n)Fixed decimals (string)
toPrecision(n)Sig digits (string)
toExponential(n)Exponential (string)
valueOf()Primitive

Conversion Functions

Function'42''3.14''42px''0xFF'
Number()423.14NaN255
parseInt()42342255
parseFloat()423.14420

Radix

RadixExampleResult
2parseInt('1010', 2)10
8parseInt('777', 8)511
10parseInt('42', 10)42
16parseInt('FF', 16)255
36parseInt('Z', 36)35

Math Rounding

MethodEffect
Math.roundNearest (half up)
Math.floorDown
Math.ceilUp
Math.truncDrop decimals

Intl.NumberFormat

StyleExample
Default1,234,567
Currency$1,234.50
Percent25%
Unit5 km

Best Practices

Do This:

// Use Number() for strict coercion
Number('42');                                   // ✅

// Use parseInt with radix
parseInt('08', 10);                             // ✅

// Use Number.isNaN
Number.isNaN(x);                                // ✅

// Use Number.isInteger
Number.isInteger(42);                           // ✅

// Compare floats with epsilon
Math.abs(a - b) < Number.EPSILON;               // ✅

// Use toFixed for display
price.toFixed(2);                               // ✅

// Use Intl.NumberFormat for locale
new Intl.NumberFormat('en-US');                 // ✅

// Use BigInt for very large integers
9007199254740993n;                              // ✅

// Round with a helper
function round(n, p) { ... }                    // ✅

Don’t Do This:

// Don't use global isNaN — it coerces
isNaN('hello');                                 // ❌ true (surprising)
Number.isNaN('hello');                          // ✅ false

// Don't parseInt without radix
parseInt('08');                                 // ⚠️  engine-dependent
parseInt('08', 10);                             // ✅

// Don't compare floats with ===
0.1 + 0.2 === 0.3;                              // ❌ false
Math.abs(0.1 + 0.2 - 0.3) < 1e-9;               // ✅

// Don't use toFixed for math
Number((0.1 + 0.2).toFixed(2));                 // ⚠️  string roundtrip

// Don't trust MAX_SAFE_INTEGER+1
Number.MAX_SAFE_INTEGER + 1;                    // ⚠️  precision loss

// Don't parseFloat a hex string
parseFloat('0xFF');                             // ❌ 0

// Don't use parseInt for floats
parseInt('3.14');                               // ❌ 3

// Don't expect Number('') to be NaN
Number('');                                     // ⚠️  0

Common Pitfalls

PitfallProblemSolution
0.1 + 0.2Floating-point errorUse epsilon compare
isNaN('x')Coerces — misleadingUse Number.isNaN
parseInt without radixEngine-dependentAlways pass radix
Number('')Returns 0, not NaNCheck string first
Number(undefined)NaNGuard inputs
parseInt('3.14')Truncates to 3Use parseFloat
parseFloat('0xFF')Returns 0Use parseInt(x, 16)
Precision past 2^53Wrong resultsUse BigInt
toFixed returns stringType mismatchWrap with Number()
-0 === 0True but differentUse Object.is

Real-World Examples

1. Parse a Number

console.log(Number('42'));
// [ 42 ]

2. Parse Int with Radix

console.log(parseInt('FF', 16));
// [ 255 ]

3. Parse Float

console.log(parseFloat('3.14abc'));
// [ 3.14 ]

4. Check Integer

console.log(Number.isInteger(42));
// [ true ]

5. Check NaN

console.log(Number.isNaN(NaN));
// [ true ]

6. Check Finite

console.log(Number.isFinite(42));
// [ true ]

console.log(Number.isFinite(Infinity));
// [ false ]

7. Fixed Decimals

console.log((3.14159).toFixed(2));
// [ '3.14' ]

8. Convert to Hex

console.log((255).toString(16));
// [ 'ff' ]

9. Float Comparison

console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);
// [ true ]

10. Round to Decimals

function round(n, p) {
  const f = 10 ** p;
  return Math.round(n * f) / f;
}

console.log(round(3.14159, 2));
// [ 3.14 ]

11. Clamp

function clamp(n, min, max) {
  return Math.min(Math.max(n, min), max);
}

console.log(clamp(15, 0, 10));
// [ 10 ]

12. Random Integer

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

13. Currency Format

const fmt = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD'
});

console.log(fmt.format(1234.5));
// [ '$1,234.50' ]

14. Thousands Separator

console.log(new Intl.NumberFormat('en-US').format(1234567));
// [ '1,234,567' ]

15. Percentage

console.log(new Intl.NumberFormat('en-US', { style: 'percent' }).format(0.25));
// [ '25%' ]

16. Format Bytes

function formatBytes(b) {
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let i = 0;
  while (b >= 1024 && i < units.length - 1) {
    b /= 1024;
    i++;
  }
  return `${b.toFixed(2)} ${units[i]}`;
}

console.log(formatBytes(1536));
// [ '1.50 KB' ]

17. Safe Parse

function safeParseInt(str, radix = 10) {
  const n = parseInt(str, radix);
  return Number.isNaN(n) ? null : n;
}

console.log(safeParseInt('hello'));
// [ null ]

18. BigInt

const big = 9007199254740993n;
console.log(big + 1n);
// [ 9007199254740994n ]

19. Binary / Octal / Hex Output

console.log((10).toString(2));
// [ '1010' ]

console.log((8).toString(8));
// [ '10' ]

console.log((255).toString(16));
// [ 'ff' ]

20. Full Script

const n1_50 = 42;
const n2_50 = 3.14;
const n3_50 = 0b1010;
const n4_50 = 0o777;
const n5_50 = 0xFF;
const n6_50 = 1_000_000;

console.log(Number('42'));
console.log(Number('3.14'));
console.log(Number(''));

console.log(parseInt('42'));
console.log(parseInt('42px'));
console.log(parseInt('FF', 16));

console.log(parseFloat('3.14'));
console.log(parseFloat('3.14abc'));

console.log(Number.isInteger(42));
console.log(Number.isInteger(3.14));
console.log(Number.isNaN(NaN));
console.log(Number.isFinite(42));
console.log(Number.isFinite(Infinity));

console.log(Number.MAX_SAFE_INTEGER);
console.log(Number.MIN_SAFE_INTEGER);
console.log(Number.MAX_VALUE);
console.log(Number.EPSILON);

console.log((3.14159).toFixed(2));
console.log((255).toString(16));
console.log((3.14).toPrecision(2));
console.log((1234.5678).toExponential(2));

Visual: Number Type

┌──────────────────────────────────────────────┐
│  JavaScript has ONE number type              │
│                                              │
│  ┌────────────────────────────────────────┐  │
│  │  64-bit IEEE 754 double               │  │
│  │                                        │  │
│  │  42     → 42.0                         │  │
│  │  3.14   → 3.14                         │  │
│  │  0xFF   → 255                          │  │
│  │  1e3    → 1000                         │  │
│  │  NaN    → NaN                          │  │
│  │  Infinity → ∞                          │  │
│  └────────────────────────────────────────┘  │
│                                              │
│  Except BigInt: 123n                         │
│                                              │
└──────────────────────────────────────────────┘

Visual: Conversion Functions

┌──────────────────────────────────────────────┐
│  Input: '42px'                               │
│                                              │
│  Number('42px')    → NaN                     │
│  parseInt('42px')  → 42                      │
│  parseFloat('42px')→ 42                      │
│                                              │
│  Number is STRICT.                           │
│  parseInt/parseFloat are LENIENT.            │
│                                              │
└──────────────────────────────────────────────┘

Visual: Floating-Point Quirk

┌──────────────────────────────────────────────┐
│  0.1 + 0.2 === 0.3                           │
│                                              │
│  Actual:  0.30000000000000004                │
│  Expected: 0.3                               │
│                                              │
│  IEEE 754 can't represent 0.1 exactly.       │
│  Same for 0.2. Sum accumulates error.        │
│                                              │
│  Fix: compare with epsilon                   │
│  Math.abs(a - b) < Number.EPSILON            │
│                                              │
└──────────────────────────────────────────────┘

Visual: Safe Integer Range

┌──────────────────────────────────────────────┐
│                                              │
│  ─── Safe integers ──────────────────        │
│     -2^53+1 ... 2^53-1                       │
│     ±9007199254740991                        │
│                                              │
│  Beyond that:                                │
│    Precision loss                            │
│    Use BigInt                                │
│                                              │
│  Number.isSafeInteger(x) → boolean           │
│                                              │
└──────────────────────────────────────────────┘

Summary

ConceptSyntaxExample
Decimal4242
Float3.143.14
Binary0b101010
Octal0o777511
Hex0xFF255
Exponential1e31000
Separator1_000_0001000000
CoerceNumber(x)Number('42')
Parse intparseInt(s, r)parseInt('FF', 16)
Parse floatparseFloat(s)parseFloat('3.14')
Is integerNumber.isInteger(x)true
Is NaNNumber.isNaN(x)true
Is finiteNumber.isFinite(x)true
Fixedn.toFixed(2)'3.14'
Basen.toString(16)'ff'
Precisionn.toPrecision(3)'3.14'
Exponentialn.toExponential(2)'1.23e+5'
EpsilonNumber.EPSILON~2.22e-16
Safe int maxMAX_SAFE_INTEGER2^53 – 1
BigInt123nLarge ints
FormatIntl.NumberFormatLocale

Key takeaways:

  • JavaScript has one number type — 64-bit floating-point — plus BigInt for large integers
  • All numbers are doubles — even integers
  • NaN is a numbertypeof NaN === 'number'
  • Floating-point arithmetic is imprecise — compare with Number.EPSILON
  • Safe integers go up to 2^53 – 1 — beyond that, use BigInt
  • Number() is strict — returns NaN for invalid input
  • parseInt / parseFloat are lenient — stop at the first invalid character
  • Always pass radix to parseInt — don’t rely on the default
  • Use Number.isNaN — the global isNaN coerces and misleads
  • toFixed returns a string — wrap with Number() if needed
  • toString(base) converts to hex, binary, or octal
  • Intl.NumberFormat handles locale-aware formatting — currency, percent, thousands
  • Use BigInt for integers larger than 2^53 – 1

Remember: Numbers in JavaScript are floats — always. Get comfortable with the quirks: 0.1 + 0.2 !== 0.3, NaN !== NaN, integers lose precision past 2^53. Use Number() for strict parsing, parseInt/parseFloat with radix for lenient parsing, and Number.isNaN/Number.isInteger for checks. Format with toFixed and Intl.NumberFormat. Reach for BigInt when you need exact large integers. Master numbers, and arithmetic stops surprising you.


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!