LEVIATHAN vd52e79c4 · d52e79c486

Types

decimal

The exact base-10 number for money and other decimal quantities — 34 significant digits, a kept scale, value equality and half-even rounding.

since 0.1.0-alpha.1linuxwindowswasm

Description

A decimal is an exact base-10 number. It holds a sign, a coefficient of up to 34 digits and a scale from 0 to 34, the number of digits after the point; its value is the coefficient times 10 to the minus scale. 0.1 + 0.2 is exactly 0.3, which float cannot say, so prices, ledgers and other base-10 quantities use decimal.

  • The scale is kept. 9.90 prints as 9.90, 2 * 9.90 as 19.80 and 1.10 * 1.10 as 1.2100. toString() always writes exactly scale() digits after the point and never an exponent.
  • Equality is by value. 1.0 == 1.00 is true, and 1.0 and 1.00 are the same Map key and the same Set element.
  • A decimal mixes only with decimal. An int or float value is converted with toDecimal(), and a decimal goes back with toInt() or toFloat(). Literals still adopt decimal from their context, so price * 2 and decimal d = 5; need no call.
  • A literal ending in m (19.99m) is a decimal in every context. Every decimal literal is built exactly from its digits, never through a binary float.

decimal is a primitive: it needs no import, and it defaults to 0 (scale 0).

Exact money arithmetic

use io::console;

decimal price = 19.99;
int qty = 3;
decimal total = price * qty.toDecimal();
console.writeln(total);
console.writeln(0.1m + 0.2m == 0.3m);
console.writeln(9.90m * 2);
console.writeln(1.0m == 1.00m);
console.writeln(total / 4);
console.writeln((total / 4).round(2));
console.writeln(1m / 3);
decimal tax;
console.writeln(tax);
59.97
true
19.80
true
14.9925
14.99
0.3333333333333333333333333333333333
0

Rules

Values.

  • A decimal's coefficient has at most 34 digits and its scale is 0 to 34. Zero is always positive: -0.0m is 0.0.
  • Two decimals are equal when their values are equal, whatever their scales. The scale shows only in toString(), scale() and the results of the operations below.

The fit rule. Every operation computes its exact result and an ideal scale, then:

  1. if the exact result can be written with at most 34 digits at some scale from 0 to 34, it is kept exactly, at the scale nearest to the ideal one;
  2. otherwise it is rounded half to even to 34 significant digits (or to 34 digits after the point when it is small);
  3. if no scale can hold it, the operation throws decimal overflow.
operation ideal scale can throw
a + b, a - b the larger of the two scales decimal overflow
a * b the sum of the scales decimal overflow
a / b a's scale minus b's division by zero, decimal overflow
a % b the larger of the two scales modulo by zero
-a a's scale —
  • % is the truncated remainder: the result has the dividend's sign (-7m % 2 is -1) and is always exact.
  • / keeps an exact quotient at the scale nearest a.scale() - b.scale() (10.00m / 2 is 5.00, 1m / 4 is 0.25, 100m / 0.5m is 200); a quotient that does not terminate gets 34 significant digits (2m / 3 is 0.6666666666666666666666666666666667).
  • ==, !=, <, <=, > and >= compare values.
  • There is no &, |, ^, <<, >>, ~ or ! on decimal.

Typing.

  • An operator with a decimal on one side and any other numeric type on the other is a compile error: 19.99m * n with an int n asks for n.toDecimal(), and a float operand asks for .toDecimal() or .toFloat(). A literal operand adopts decimal instead.
  • No numeric value converts into or out of decimal at a typed boundary (a declaration, field, parameter, return, element, assignment or compound store): decimal e = n; and int i = d; are compile errors that name the call to write. decimal? d = 1.5; holds a decimal; None fills a decimal? as any optional.
  • In a compound assignment the operator comes first: d += n with an int n is the operator error, n += d is the store error, and d += 1 is fine.
  • Literals:
    • an integer or float literal adopts decimal wherever its context is decimal: a declared type, a parameter, a return, a field, an element, a decimal operand beside it, or a match subject;
    • an expression made only of literals adopts it as a whole and is computed in decimal at compile time, so decimal r = 5 / 100; is 0.05; a step that overflows or divides by zero is a compile error;
    • a literal that is not exactly representable (more than 34 significant digits, or a nonzero digit past the 34th place) is a compile error at the literal;
    • a literal with the m suffix is decimal everywhere and never adopts another type (float f = 1.5m; and int i = 1m; are errors);
    • an expression only decimal can compute adopts it too: decimal r = 7.5 % 2; is 1.5;
    • a hexadecimal or binary literal adopting decimal is the exact unsigned value of its digits: decimal d = 0xFFFFFFFFFFFFFFFF; is 18446744073709551615.
  • Overloads: f(1.5m) picks f(decimal); a bare f(1.5) keeps preferring f(float). An int variable never selects f(decimal).
  • A conditional, match, array literal or ?? never widens across numeric types: c ? price : 0 is a decimal (the literal adopts) and [1.5m, 2, 3.25] is an Array<decimal>, but c ? price : qty with an int qty is an error.
  • match on a decimal compares value and range arms by value; their literals adopt decimal. An else arm is needed. A decimal pattern (1.5m =>, 0m..2m =>) on a subject of another numeric type is a compile error, like the operator it stands for.
  • decimal is a distinct union member: int | decimal keeps 1 and 1m apart, and is decimal narrows. At run time a decimal never equals a value of another kind (== is false, != is true), ordering it against another kind is always false, and a range arm of another kind does not match it. A decimal is not marshalable to C.
  • A range (a..b) holds ints: decimal bounds are a compile error, and a range never fills an Array<decimal> or a decimal loop variable (convert each element with toDecimal()).

Conversions.

call result throws
n.toDecimal() on any integer type exact, scale 0 —
f.toDecimal() on any float type the shortest digits that convert back to exactly f float is not finite for toDecimal(); float out of decimal range for toDecimal() at 10^34 and above
d.toInt() truncated toward zero decimal out of int64 range for toInt()
d.toFloat() the nearest float, ties to even —
s.toDecimal() on a string the exact value of the text, or None —

0.1.toDecimal() is 0.1, not the float's full binary expansion. The shortest digits depend on the format's precision: a float16 65504 converts to 65500, and the float8 maximum 448 to 450. string.toDecimal() reads an optional -, digits with an optional point and fraction, and an optional exponent ("1.5e-3" is 0.0015); it accepts no +, no whitespace and no _, and it never rounds: text it cannot hold exactly gives None.

Rounding. round(), round(places) and round(places, mode) round to places digits after the point (0 to 34) by a RoundingMode, half to even when no mode is given. floor(), ceil() and trunc() round to a whole number toward negative infinity, positive infinity and zero.

Examples

Rounding modes, scales and conversions:

Rounding, scale and conversions

use io::console;

decimal x = 2.345;
console.writeln(x.round(2));
console.writeln(x.round(2, RoundingMode::HalfAwayFromZero));
console.writeln((2.5m).round());
console.writeln((-1.25m).floor());
console.writeln((1.5m).round(3));
console.writeln((1.50m).normalize());
console.writeln((1.10m).pow(2));
console.writeln((2m).pow(-2));
console.writeln((19.99m).toInt());
console.writeln((0.1 + 0.2).toDecimal());
console.writeln("19.990".toDecimal() ?? 0m);
console.writeln("+1".toDecimal() == None);
2.34
2.35
2
-2
1.500
1.5
1.2100
0.25
19
0.30000000000000004
19.990
true

Literals and the typing rules:

Literals adopt decimal

use io::console;

decimal half(decimal x) => x / 2;

void demo() {
    decimal r = 5 / 100;
    console.writeln(r);
    console.writeln(half(5));
    Array<decimal> xs = [1.5m, 2, 3.25];
    console.writeln(xs);
    decimal price = 9.99;
    bool member = true;
    decimal charged = member ? price : 0;
    console.writeln(charged);
    decimal d = 1.25;
    d += 1;
    console.writeln(d);
    int n = 4;
    d += n.toDecimal();
    console.writeln(d);
    string band = match (d) {
        0..5 => "small",
        else => "large"
    };
    console.writeln(band);
}
demo();
0.05
2.5
[1.5, 2, 3.25]
9.99
2.25
6.25
large

Run-time failures throw a RuntimeException with a fixed message:

Overflow and division by zero

use io::console;

decimal big = 9999999999999999999999999999999999m;
decimal zero = 0;
try {
    console.writeln(big + 1);
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
try {
    console.writeln(big / zero);
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
try {
    console.writeln((1.5m).round(35));
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
caught: decimal overflow
caught: division by zero
caught: round: places must be in 0..34

Notes

  • Literals adopt decimal, values do not: with an int n, decimal share = n / 100; is a compile error, because n / 100 is an int value. Write n.toDecimal() / 100. A literal-only expression is different: decimal r = 5 / 100; is 0.05.
  • decimal.round() rounds ties to even (2.5 becomes 2); float.round() rounds them away from zero.
  • An array of a struct whose fields are numbers, bool, char and decimal is stored by column on native builds, sixteen bytes per decimal value (lang.columnar-arrays); the layout is not observable.
  • The run-time messages are exact on every engine: decimal overflow, division by zero, modulo by zero, decimal out of int64 range for toInt(), float is not finite for toDecimal(), float out of decimal range for toDecimal() and round: places must be in 0..34.

See also

  • Numeric conversions and working types — Values cross between integer and float types only through a conversion call, lossless widening is implicit, and literals take the type their context asks for.
  • Sized floats: float8, float16, float32 — The narrow floating-point formats, how every operation re-rounds, and where they overflow or throw.
  • Numeric literals — Decimal, hexadecimal and binary integers, floats, the m suffix of a decimal literal, and the _ digit separator.
  • Columnar storage of struct arrays — How native builds lay out an array of simple structs column by column, when that applies, and how to turn it off.
  • decimal — An exact base-10 number: up to 34 significant digits and up to 34 digits after the point.
  • RoundingMode — How a decimal is rounded when digits are dropped.