Parsing, checking, and formatting JavaScript numbers, plus common Math operations.

Basics

Introduction

JavaScript numbers are 64-bit floats (IEEE 754), so 0.1 + 0.2 is not exactly 0.3; use BigInt beyond 2^53.

  • Number (developer.mozilla.org)
  • Math (developer.mozilla.org)

Literals

42          // → 42
3.14        // → 3.14
0xff        // → 255 (hex)
0b1010      // → 10 (binary)
0o755       // → 493 (octal)
1_000_000   // → 1000000 (numeric separators)
1e3         // → 1000 (exponent)
Infinity     // → Infinity
-Infinity    // → -Infinity
NaN          // → NaN (Not a Number)

Infinity and NaN are numbers too: typeof Infinity === 'number'.

See: Number literals, NaN (developer.mozilla.org)

Parsing

Number('42')           // → 42
Number('')             // → 0
Number('42px')         // → NaN
Number('3.14')         // → 3.14
parseInt('42px', 10)   // → 42
parseInt('08', 10)     // → 8
parseFloat('3.14abc')  // → 3.14
+'42'                  // → 42 (unary plus)

Number() rejects trailing junk, while parseInt() and parseFloat() stop at it. Always pass a radix to parseInt().

See: parseInt(), parseFloat(), Number() (developer.mozilla.org)

Checking

Number.isInteger(2)              // → true
Number.isInteger(2.5)            // → false
Number.isFinite(Infinity)        // → false
Number.isNaN('x')                // → false
Number.isSafeInteger(2 ** 53)    // → false
Number.MAX_SAFE_INTEGER          // → 9007199254740991
Number.EPSILON                   // → 2.220446049250313e-16

The global isNaN('x') coerces its argument and returns true; Number.isNaN('x') is false.

See: Number.isInteger(), Number.isNaN(), Number.isSafeInteger() (developer.mozilla.org)

Operations

Rounding

Math.round(4.5)     // → 5
Math.round(-4.5)    // → -4
Math.floor(4.7)     // → 4
Math.floor(-4.7)    // → -5
Math.ceil(4.2)      // → 5
Math.trunc(4.7)     // → 4 (drop the fraction)
(2.5).toFixed(0)            // → "3"
(0.1 + 0.2).toFixed(2)      // → "0.30"
(1.005).toFixed(2)          // → "1.00" (really 1.00499...)

toFixed() returns a string, and binary floats can make decimal rounding surprising.

See: Math.round(), Math.trunc(), toFixed() (developer.mozilla.org)

Math

Math.abs(-3)          // → 3
Math.min(1, 2, 3)     // → 1
Math.max(1, 2, 3)     // → 3
Math.pow(2, 10)       // → 1024
Math.sqrt(16)         // → 4
Math.cbrt(27)         // → 3
Math.sign(-3)         // → -1
Math.hypot(3, 4)      // → 5
Math.PI               // → 3.141592653589793
Math.random()        // → 0 <= n < 1
Math.random() * 10   // → 0 <= n < 10

Math.random() is not cryptographically secure; use crypto.getRandomValues() for tokens and keys.

See: Math, Math.random(), Crypto.getRandomValues() (developer.mozilla.org)

Formatting

const n = 1234567.891

n.toLocaleString('en-US')   // → "1,234,567.891"
const fmt = (opts) => new Intl.NumberFormat('en-US', opts)

fmt({ style: 'currency', currency: 'USD' }).format(1234.5)
// → "$1,234.50"
fmt({ style: 'percent' }).format(0.25)      // → "25%"
fmt({ notation: 'compact' }).format(12345)  // → "12K"
fmt({ style: 'unit', unit: 'kilometer' }).format(5)  // → "5 km"
(3.14159).toPrecision(3)   // → "3.14"
(12345).toExponential(2)   // → "1.23e+4"

toPrecision() and toExponential() return strings; locale output varies by runtime and locale.

See: Intl.NumberFormat, toLocaleString(), toPrecision() (developer.mozilla.org)

BigInt

123n             // → 123n
typeof 1n        // → 'bigint'
BigInt('123')    // → 123n
BigInt(123)      // → 123n
10n + 3n         // → 13n
10n / 3n         // → 3n (truncates)
1n < 2           // → true
1n + 1           // TypeError: Cannot mix BigInt and other types

BigInt holds arbitrarily large integers. Comparisons work across types, but mixing a BigInt and a Number in arithmetic throws.

See: BigInt, typeof (developer.mozilla.org)

0 Comments for this cheatsheet. Write yours!