Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Numbers & operators

TypeScript docs MDN Number ↗

Choose a numeric type

TypeScript

number uses IEEE 754 double precision; bigint holds arbitrary-size integers (ES2020+). The two do not mix in arithmetic without conversion. boolean holds true or false; it is not an integer type.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const ratio: number = 1.5;
const whole: bigint = 24n;
const ready: boolean = true;

Recognize limits and overflow

TypeScript

Integer arithmetic on number can lose precision beyond the safe-integer range. Very large floating-point results can become Infinity. bigint avoids fixed-width integer overflow; it has no fractional part.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const safe = Number.isSafeInteger(24);
const maximum = Number.MAX_SAFE_INTEGER;
const exact = 9007199254740993n;

Read arithmetic, comparisons and bit operations

TypeScript

/ on number can produce fractions; ** exponentiates. === compares without coercion. Bitwise number operations use 32-bit integers; bigint has separate integer operations and no unsigned >>>.

Fragment

Fragment: imports and type/function declarations at file scope; usage statements inside a function.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const quotient = 7 / 2; // 3.5
const square = 3 ** 2;
const enabled = (0b1010 & 0b0010) !== 0;

Detect integer overflow: safe integers, math/bits, checked_*, __builtin_add_overflow

TypeScript

Beyond the limits in Recognize limits and overflow, this shows a checked add at run time and the tools for wrapping on purpose. number is an IEEE 754 double, so integers are exact only between -(2^53 - 1) and 2^53 - 1 (Number.MAX_SAFE_INTEGER). Past that, arithmetic does not throw or wrap: results silently round to the nearest representable double, and adjacent integers start to compare equal. Number.isSafeInteger tells you whether a value is still exact. bigint has no upper limit, and BigInt.asIntN / asUintN wrap a bigint to a chosen bit width when you want fixed-width behavior on purpose.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// number is a double: integers are exact only up to 2^53 - 1.
const max = Number.MAX_SAFE_INTEGER; // 9007199254740991
assert.equal(max + 1, max + 2); // both round to 2^53: precision is lost silently

// Checked addition: reject results outside the safe-integer range.
function checkedAdd(a: number, b: number): number {
  const sum = a + b;
  if (!Number.isSafeInteger(a) || !Number.isSafeInteger(b) || !Number.isSafeInteger(sum)) {
    throw new RangeError(`${a} + ${b} is outside the safe integer range`);
  }
  return sum;
}

assert.equal(checkedAdd(40, 2), 42);
assert.throws(() => checkedAdd(max, 1), RangeError);

// Emulating fixed-width types: | 0 and >>> 0 wrap to int32 and uint32.
assert.equal((2_147_483_647 + 1) | 0, -2_147_483_648);
assert.equal((0xffff_ffff + 1) >>> 0, 0);

// BigInt never overflows; BigInt.asIntN/asUintN wrap to a chosen width on purpose.
const big = BigInt(max) + 2n;
assert.equal(big, 9_007_199_254_740_993n);
assert.equal(BigInt.asUintN(64, 2n ** 64n + 5n), 5n);
assert.equal(BigInt.asIntN(8, 128n), -128n);

console.log('safe max:', max, 'as bigint + 2:', big.toString());

In practice: validate counters, IDs and money totals with Number.isSafeInteger at the boundary where they enter the program, and switch to bigint (or keep 64-bit IDs as strings) when values can exceed 2^53. Use | 0 or >>> 0 only when you deliberately want 32-bit wraparound, such as in hash functions.

A 64-bit integer ID parsed from JSON with JSON.parse becomes a number and may already be rounded; ask the API for strings or use a reviver on the raw text.

Bitwise operators convert their operands to 32-bit integers first, so x | 0 on a value above 2^31 changes it.

Divide integers and take remainders: / and %, Math.trunc, rem_euclid, divide by zero

TypeScript

Beyond the operator summary in Read arithmetic, comparisons and bit operations, this covers integer quotients, negative remainders, Euclidean modulo and division by zero. / on number is always floating-point division, so 7 / 2 is 3.5. Integer division needs an explicit rounding step: Math.trunc rounds toward zero (what C, Go and Rust do), Math.floor rounds toward negative infinity (what Python does). % is a remainder whose sign follows the dividend, so -7 % 3 is -1. Dividing a number by zero never throws: it gives Infinity, -Infinity or NaN. bigint division truncates toward zero and throws a RangeError on division by 0n.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// / on number is always floating-point division.
assert.equal(7 / 2, 3.5);

// Integer division: Math.trunc rounds toward zero (like C, Go, Rust);
// Math.floor rounds toward negative infinity. They differ for negatives.
assert.equal(Math.trunc(-7 / 2), -3);
assert.equal(Math.floor(-7 / 2), -4);

// % is a remainder: its sign follows the dividend.
assert.equal(-7 % 3, -1);

// Euclidean modulo: always in [0, n) for positive n (wrap-around indexes, clocks).
const mod = (a: number, n: number): number => ((a % n) + n) % n;
assert.equal(mod(-7, 3), 2);
assert.equal(mod(-1, 24), 23);

// Dividing by zero does not throw on number.
assert.equal(1 / 0, Infinity);
assert.equal(-1 / 0, -Infinity);
assert.ok(Number.isNaN(0 / 0));
assert.ok(Number.isNaN(5 % 0));

// BigInt division truncates toward zero, and dividing by 0n throws.
assert.equal(-7n / 2n, -3n);
assert.equal(-7n % 3n, -1n);
assert.throws(() => 1n / 0n, RangeError);

console.log(7 / 2, Math.trunc(-7 / 2), -7 % 3, mod(-7, 3), 1 / 0);

In practice: write Math.trunc(a / b) for integer quotients and ((a % n) + n) % n for an always-positive modulo, such as wrapping an array index or an hour of the day. Check divisors that come from input, because Infinity and NaN propagate quietly through later arithmetic.

Math.trunc(a / b) is exact only while a / b stays a safe integer; for very large values use bigint division.

~~(a / b) and (a / b) | 0 also truncate but wrap outside the 32-bit range.

Convert between numeric types: Math.trunc, T(x), as + TryFrom, static_cast

TypeScript

Beyond the type list in Choose a numeric type, this covers converting values: rounding to an integer, fitting a fixed width, and moving between number and bigint. There is only one number type, so converting means choosing how to round: Math.trunc (toward zero), Math.floor, Math.ceil or Math.round (half toward +Infinity, so -2.5 becomes -2). Number() converts strings, booleans and bigint, and returns NaN when it cannot. Fixed-width behavior appears only where you ask for it: bitwise operators wrap to 32 bits, typed arrays wrap (Uint8Array) or clamp (Uint8ClampedArray) on store, and BigInt() and Number() convert between number and bigint.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// There is one number type, so "casting" means choosing how to round.
assert.equal(Math.trunc(-2.7), -2); // toward zero, like a C cast
assert.equal(Math.floor(-2.7), -3);
assert.equal(Math.round(2.5), 3);
assert.equal(Math.round(-2.5), -2); // rounds half toward +Infinity

// Number() converts other values; check the result before trusting it.
assert.equal(Number('42'), 42);
assert.equal(Number(true), 1);
assert.ok(Number.isNaN(Number('4x')));

// Fit into a fixed width on purpose: wrap with bit operations, or clamp.
assert.equal(300 & 0xff, 44); // like a uint8 cast
assert.equal(2 ** 32 + 5 | 0, 5); // like an int32 cast
const clampU8 = (n: number): number => Math.min(255, Math.max(0, Math.trunc(n)));
assert.equal(clampU8(300), 255);
assert.equal(clampU8(-4.5), 0);

// Typed arrays apply the conversion when you store into them.
const bytes = new Uint8Array([300, -1]);
const clamped = new Uint8ClampedArray([300, -1, 1.5]);
assert.deepEqual([...bytes], [44, 255]); // wraps
assert.deepEqual([...clamped], [255, 0, 2]); // clamps and rounds half to even

// number <-> bigint conversion is explicit, and BigInt() rejects fractions.
assert.equal(BigInt(42), 42n);
assert.throws(() => BigInt(1.5), RangeError);
assert.equal(Number(2n ** 64n), 18446744073709552000); // rounds to the nearest double

console.log(Math.trunc(-2.7), [...bytes], [...clamped]);

In practice: name the rounding you want instead of relying on parseInt or | 0, clamp explicitly with Math.min/Math.max before storing into a narrower range, and remember that Number(bigint) rounds when the value is above 2^53.

BigInt(1.5) throws a RangeError; round first with Math.trunc if you mean to drop the fraction.

Math.round(-2.5) is -2, while Rust's round() and C++ std::lround give -3 (half away from zero).

Compare floats and keep money in integer cents: EPSILON, math.IsNaN, total_cmp, std::signbit

TypeScript

Beyond the type list in Choose a numeric type and the decimal libraries in Big numbers & decimals, this covers comparing computed floats, NaN, negative zero and keeping money in integer cents. number is an IEEE 754 binary64 double. Decimal fractions such as 0.1 have no exact binary representation, so 0.1 + 0.2 is 0.30000000000000004 and === comparisons on computed values fail. NaN is not equal to anything, itself included; Number.isNaN and Object.is detect it. -0 === 0 is true, but Object.is and 1 / -0 can tell them apart. Number.EPSILON is the gap between 1 and the next double, which is the right tolerance only near 1.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// number is an IEEE 754 binary double: 0.1 has no exact representation.
assert.notEqual(0.1 + 0.2, 0.3);
console.log(0.1 + 0.2); // 0.30000000000000004

// Compare with a tolerance: relative for large values, absolute near zero.
function nearlyEqual(a: number, b: number, rel = 1e-9, abs = 1e-12): boolean {
  return Math.abs(a - b) <= Math.max(rel * Math.max(Math.abs(a), Math.abs(b)), abs);
}
assert.ok(nearlyEqual(0.1 + 0.2, 0.3));
assert.ok(nearlyEqual(1e20 + 1e5, 1e20));
assert.ok(!nearlyEqual(1.0, 1.001));
console.log('epsilon:', Number.EPSILON); // gap between 1 and the next double

// NaN is not equal to anything, including itself.
const nan = 0 / 0;
assert.ok(nan !== nan); // TypeScript rejects a literal NaN === comparison outright
assert.ok(Number.isNaN(nan) && Object.is(nan, NaN));
assert.ok([NaN].includes(NaN)); // includes uses SameValueZero
assert.equal([NaN].indexOf(NaN), -1); // indexOf uses ===

// -0 equals 0 but is observable.
assert.ok(-0 === 0 && !Object.is(-0, 0));
assert.equal(1 / -0, -Infinity);

// Money: keep integer cents (or use a decimal library), round once at the edge.
const priceCents = 1999;
const totalCents = priceCents * 3;
const taxCents = Math.round((totalCents * 825) / 10_000); // 8.25%
assert.equal(totalCents + taxCents, 6492);
console.log('total:', ((totalCents + taxCents) / 100).toFixed(2));

In practice: compare computed floats with a relative tolerance plus a small absolute one for values near zero. For money, store integer cents (or bigint for large totals) and round once when displaying, or use a decimal library. Use Number.isNaN, never x === NaN.

For decimal money arithmetic, decimal.js (10.6.0) and big.js are the common libraries; they keep values as decimal digits instead of binary fractions.

Array.prototype.includes finds NaN (SameValueZero) but indexOf does not (===).

TypeScript reports x === NaN as an error (TS2845) because the condition is always false.

Parse and format numbers: Number + Intl.NumberFormat, strconv + fmt, parse + format!, from_chars + std::format

TypeScript

Beyond the basic calls in Text ↔ number conversion and Printing & formatting, this covers what each parser accepts, a strict parser, and output precision, rounding and separators. Number(text) parses the whole string but has loose rules: whitespace is trimmed, '' becomes 0 and hex such as '0x1f' is accepted. parseInt and parseFloat read a prefix and ignore the rest, so parseInt('12px') is 12 and parseInt('1e3') is 1. Neither throws; failure is NaN. For output, toFixed(n) gives fixed decimals, padStart pads, and Intl.NumberFormat handles thousands separators, currencies and locales.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// Number() parses the whole string, but accepts some surprising inputs.
assert.equal(Number('42'), 42);
assert.equal(Number(' 42\n'), 42); // surrounding whitespace is ignored
assert.equal(Number(''), 0); // empty string is 0, not an error
assert.equal(Number('0x1f'), 31);
assert.ok(Number.isNaN(Number('12px')));

// parseInt stops at the first bad character and ignores the rest.
assert.equal(parseInt('12px', 10), 12);
assert.equal(parseInt('1e3', 10), 1);
assert.equal(parseFloat('3.14abc'), 3.14);

// A strict integer parser: validate the shape, then check the range.
function parseIntStrict(text: string): number {
  if (!/^[+-]?\d+$/.test(text)) throw new SyntaxError(`not an integer: ${JSON.stringify(text)}`);
  const n = Number(text);
  if (!Number.isSafeInteger(n)) throw new RangeError(`out of range: ${text}`);
  return n;
}
assert.equal(parseIntStrict('-120'), -120);
assert.throws(() => parseIntStrict(''), SyntaxError);
assert.throws(() => parseIntStrict('12px'), SyntaxError);
assert.throws(() => parseIntStrict('9007199254740993'), RangeError);

// Formatting.
assert.equal((1234.5).toFixed(2), '1234.50');
assert.equal((1.005).toFixed(2), '1.00'); // 1.005 is really 1.00499999...
// A real tie (0.125 is exact in binary): toFixed and Intl round it away from zero
// by default, while Go, Rust and C++ formatting round it to even.
assert.equal((0.125).toFixed(2), '0.13');
const halfEven = new Intl.NumberFormat('en-US', {
  maximumFractionDigits: 2,
  roundingMode: 'halfEven'
});
assert.equal(halfEven.format(0.125), '0.12');
assert.equal(String(7).padStart(3, '0'), '007');
const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
assert.equal(usd.format(1234567.891), '$1,234,567.89');
assert.equal(new Intl.NumberFormat('de-DE').format(1234567.891), '1.234.567,891');
assert.equal((1234567).toLocaleString('en-US'), '1,234,567');

console.log(parseIntStrict('-120'), (1234.5).toFixed(2), usd.format(1234567.891));

In practice: validate input with a regular expression or a schema, then convert with Number and check Number.isSafeInteger or Number.isFinite. Always pass the radix to parseInt. Format user-facing amounts with Intl.NumberFormat rather than building separators by hand. When rounding to 2 decimals, an exact tie such as 0.125 becomes 0.13 with toFixed and Intl.NumberFormat (half away from zero); pass roundingMode: 'halfEven' to Intl.NumberFormat for banker's rounding.

toFixed rounds the binary value, so (1.005).toFixed(2) is '1.00'; round integer cents instead when exact decimal rounding matters.

Intl.NumberFormat output depends on the runtime's locale data; some locales use non-breaking spaces as group separators, so compare formatted strings carefully in tests.

Use integers wider than 64 bits: BigInt, math/big, u128, unsigned __int128

TypeScript

Beyond the overview in Big numbers & decimals, this shows bigint in use: exact large results, the rules for mixing with number, and JSON. bigint (ES2020) is a built-in arbitrary-precision integer: literals end in n, and +, -, *, /, %, ** work without overflow. It is a separate type from number: mixing them in arithmetic is a TypeError, so convert with BigInt(n) or Number(b). Division truncates toward zero and there are no fractions. Math functions do not accept bigint, and JSON.stringify throws on it.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// bigint: arbitrary-precision integers (ES2020). Literals end in n.
function factorial(n: bigint): bigint {
  let result = 1n;
  for (let i = 2n; i <= n; i++) result *= i;
  return result;
}

const f30 = factorial(30n);
assert.equal(f30.toString(), '265252859812191058636308480000000');

// The same computation with number loses the low digits.
let approx = 1;
for (let i = 2; i <= 30; i++) approx *= i;
assert.notEqual(BigInt(approx), f30);

// Mixing number and bigint is a TypeError: convert explicitly.
const n = 5;
assert.equal(BigInt(n) * 2n, 10n);

// Division truncates; there are no fractions. ** and % work as usual.
assert.equal(7n / 2n, 3n);
assert.equal(2n ** 100n % 1_000_007n, 698635n);

// Parsing and formatting.
assert.equal(BigInt('123456789012345678901234567890') + 1n, 123456789012345678901234567891n);
assert.equal((255n).toString(16), 'ff');

// JSON.stringify throws on bigint; serialize as a string.
assert.throws(() => JSON.stringify({ id: 1n }), TypeError);
assert.equal(JSON.stringify({ id: 1n }, (_k, v) => (typeof v === 'bigint' ? v.toString() : v)), '{"id":"1"}');

console.log('30! =', f30.toString());

In practice: use bigint for 64-bit IDs, exact large counts and cryptographic or combinatorial math, and keep number for everything else, since bigint arithmetic is much slower. Serialize bigint values as strings in JSON.

typeof 1n is 'bigint', and 1n == 1 is true while 1n === 1 is false.

bigint needs target ES2020 or later in tsconfig.