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.90prints as9.90,2 * 9.90as19.80and1.10 * 1.10as1.2100.toString()always writes exactlyscale()digits after the point and never an exponent. - Equality is by value.
1.0 == 1.00istrue, and1.0and1.00are the sameMapkey and the sameSetelement. - A decimal mixes only with decimal. An
intorfloatvalue is converted withtoDecimal(), and a decimal goes back withtoInt()ortoFloat(). Literals still adoptdecimalfrom their context, soprice * 2anddecimal d = 5;need no call. - A literal ending in
m(19.99m) is adecimalin every context. Every decimal literal is built exactly from its digits, never through a binaryfloat.
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.0mis0.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:
- 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;
- otherwise it is rounded half to even to 34 significant digits (or to 34 digits after the point when it is small);
- 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 % 2is-1) and is always exact./keeps an exact quotient at the scale nearesta.scale() - b.scale()(10.00m / 2is5.00,1m / 4is0.25,100m / 0.5mis200); a quotient that does not terminate gets 34 significant digits (2m / 3is0.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 * nwith anint nasks forn.toDecimal(), and afloatoperand asks for.toDecimal()or.toFloat(). A literal operand adoptsdecimalinstead. - No numeric value converts into or out of
decimalat a typed boundary (a declaration, field, parameter, return, element, assignment or compound store):decimal e = n;andint i = d;are compile errors that name the call to write.decimal? d = 1.5;holds a decimal;Nonefills adecimal?as any optional. - In a compound assignment the operator comes first:
d += nwith anint nis the operator error,n += dis the store error, andd += 1is fine. - Literals:
- an integer or float literal adopts
decimalwherever its context isdecimal: a declared type, a parameter, a return, a field, an element, a decimal operand beside it, or amatchsubject; - an expression made only of literals adopts it as a whole and is computed in decimal at compile
time, so
decimal r = 5 / 100;is0.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
msuffix isdecimaleverywhere and never adopts another type (float f = 1.5m;andint i = 1m;are errors); - an expression only
decimalcan compute adopts it too:decimal r = 7.5 % 2;is1.5; - a hexadecimal or binary literal adopting
decimalis the exact unsigned value of its digits:decimal d = 0xFFFFFFFFFFFFFFFF;is18446744073709551615.
- an integer or float literal adopts
- Overloads:
f(1.5m)picksf(decimal); a baref(1.5)keeps preferringf(float). Anintvariable never selectsf(decimal). - A conditional,
match, array literal or??never widens across numeric types:c ? price : 0is adecimal(the literal adopts) and[1.5m, 2, 3.25]is anArray<decimal>, butc ? price : qtywith anint qtyis an error. matchon a decimal compares value and range arms by value; their literals adoptdecimal. Anelsearm 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.decimalis a distinct union member:int | decimalkeeps1and1mapart, andis decimalnarrows. At run time a decimal never equals a value of another kind (==isfalse,!=istrue), ordering it against another kind is alwaysfalse, and a range arm of another kind does not match it. A decimal is not marshalable to C.- A range (
a..b) holdsints: decimal bounds are a compile error, and a range never fills anArray<decimal>or adecimalloop variable (convert each element withtoDecimal()).
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 anint n,decimal share = n / 100;is a compile error, becausen / 100is anintvalue. Writen.toDecimal() / 100. A literal-only expression is different:decimal r = 5 / 100;is0.05. decimal.round()rounds ties to even (2.5becomes2);float.round()rounds them away from zero.- An array of a struct whose fields are numbers,
bool,charanddecimalis stored by column on native builds, sixteen bytes perdecimalvalue (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()andround: 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
msuffix 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
decimalis rounded when digits are dropped.