Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Choosing a Decimal

A decimal is three choices: the integer, which sets the range; the scale, which sets the decimals and whether the compiler knows them; and, for each operation that rounds, the mode.

The Integer and the Scale

NeedTakeWhy
an amount to the cent: a balance, a payment, an invoiceD64<2>eight bytes, up to about ±9.2 × 10¹⁶
a price or a quantity to eight decimalsD64<8>eight bytes, up to about ±9.2 × 10¹⁰
a token’s amount at eighteen decimals, or a large notionalD128<18>sixteen bytes, up to about ±1.7 × 10²⁰
the exact product of two D64swiden them firsta D128 at the sum of their scales holds every product of two i64s
a value that is never negativeUD64 and its siblingsthe type refuses a negative value, and a u64 holds twice an i64’s largest value
millions of values in memorythe narrowest that holds thema D32<2> holds ±21 million in four bytes, sixteen to a 64-byte cache line

The scale:

NeedTakeWhy
a scale known when the code is writtenFixed<D>no bytes, two scales that never mix by accident, and every operation at its fastest
a scale learned as the program runs: a venue’s, a column’sDynamica byte beside the steps, and two scales that line up exactly

A program that learns its scales at run time can still keep each in a type where the values of one scale gather: a book of one instrument, or a column of one table. Run-Time Scales converts between the two.

The Rounding Mode

NeedTake
a mode the code namesits type: HalfEven, Floor and the rest
a mode a configuration, a venue or a protocol choosesa Rounding
a rule that names the nearest centHalfEven, banker’s rounding, or HalfExpand, the school’s, as the rule says
a fee or a margin a business must not underchargeCeil, or Expand for both signs
a size an account must be able to pay forFloor, or Trunc for both signs

Division

NeedTake
a quotient truncated, as an integer’s/
a quotient roundeddiv_round, with a mode
a quotient at another scalediv_round_to
many quotients by one divisora Divisor, prepared once
a share: a × b / c, rounded oncemul_div_round

Performance measures what each choice costs.