Types
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.
since 0.1.0-alpha.1linuxwindowswasm
Description
The numeric types form three classes:
- the integers:
byte,int8,int16,int32,uintandint; - the floats:
float8,float16,float32andfloat; decimal, the exact base-10 number (lang.decimal), a class of its own.
Three rules decide how they combine.
- A value never crosses between the classes on its own. Turning an integer into a float, or a float into an integer, is always a call:
.toFloat(),.toInt(), or a width-specific conversion such as.toFloat32(). An operator with an integer value on one side and a float value on the other is a compile error, and so is storing a value of one class into a slot of the other. - Inside a class, lossless widening is implicit and narrowing is a call. An
int8flows into anintand afloat32into afloatwithout a call. Going the other way, such asinttoint8orfloattofloat32, needs the conversion method, which throws when the value does not fit. - Literals take the type their context asks for, and so do expressions made only of literals:
float f = 1 / 3;is0.333333, because both literals become floats. With no context, integer literals areintand float literals arefloat, sovar x = 1 / 3;is0.
Every compile error caused by these rules names the conversion to write. decimal follows the same three rules, and since it is alone in its class nothing ever widens into or out of it: every crossing is .toDecimal() (on every integer and float type) or .toInt() / .toFloat() (on decimal).
Values, widening and literals
use io::console;
void demo() {
int n = 10;
float mean = n.toFloat() / 4;
console.writeln(mean);
int8 small = 100;
int wide = small;
console.writeln(wide + 1);
float third = 1 / 3;
console.writeln(third);
var whole = 1 / 3;
console.writeln(whole);
console.writeln(2.7.toInt());
}
demo();
2.5e0
101
3.333333333333333e-1
0
2
Rules
Classes and widening.
- These are the only conversions that happen without a call:
- Each of them keeps every value exactly. Every other pair inside a class needs a conversion call, and so does every pair across the classes. This includes
int8 ↔ byte,uint → int32and every narrowing. decimalwidens to nothing and nothing widens to it..toDecimal()exists on every integer and float type;decimalhas.toInt()(truncating) and.toFloat().- The conversion methods come in two kinds.
toInt()andtoFloat()exist on every numeric type. The narrow-integer conversions (toByte(),toInt8(),toInt16(),toInt32(),toUint()) are methods ofint, and the narrow-float ones (toFloat8(),toFloat16(),toFloat32()) are methods offloatand, parsing text, ofstring. Other pairs go through that hub, for examplef.toInt().toInt8()orn.toFloat().toFloat32(). The diagnostic spells the whole route. - A narrowing conversion throws a catchable
RuntimeExceptionwhen the value does not fit.floatto an integer truncates toward zero, and throws for NaN, infinity or a value outside the range.
Operators.
- Two integers compute in the joined integer type:
- Two floats compute in the wider float. An integer and a float have no join:
a * 1.5with anint8 ais a compile error that asks fora.toFloat(). - Two decimals compute in
decimal. A decimal and any other numeric type have no join:d * nwith anint nis a compile error,no implicit conversion between 'decimal' and 'int'; convert the int with .toDecimal(); with a float type the hint isconvert one operand with .toDecimal() or .toFloat().%exists ondecimal(the truncated remainder); the bitwise operators and shifts do not. - The result is reduced to the working type. Integer operators wrap at the working width, and narrow-float operators re-round in the working format. See
lang.sized-integersandlang.sized-floats. /is typed by its operands: integer division for integers, float division for floats.- Comparisons follow the same pairing rules and return
bool. +with astringoperand is not numeric. Either order converts the other operand to text and concatenates:"n=" + 5and5 + "n"are strings.
Typed boundaries.
- Each of these is a boundary, where the incoming value must already have the slot's type or widen to it:
- an explicitly typed declaration, field, parameter, return value or assignment;
- a collection element or a
for-invariable; - a lambda's written return type;
- a generic parameter after substitution;
- the store of a compound assignment.
- The value is computed in its own working type and then widened once.
int x = a * 100;with anint8 aof5computes theint8product, which wraps to-12, and only then widens it. - A compound assignment stores its working type back into the variable.
total += a;with anint totaland anint8 ais fine.x += n;with anint8 xand anint nis a compile error that asks forn.toInt8(). - With a typed target, each arm of a conditional (
c ? a : b), of amatchand of??meets the target on its own. - A numeric optional such as
float?keepsNoneand checks a present value like any other. - A boundary never converts into or out of
decimal. Another numeric type into a decimal slot iscannot convert 'int' to 'decimal' implicitly; use .toDecimal(); a decimal into another numeric slot iscannot convert 'decimal' to 'int' implicitly; use .toInt()(use .toFloat()for a float slot,use .toInt() and a width conversionfor a sized integer). For compound assignment,d += nwith anint nis the operator error andn += dthe store error.
Literals.
- A literal-only expression is numeric literals combined with unary
-and~, the arithmetic operators and the bitwise operators. It adopts the type of its context. The contexts are:- every typed boundary above;
- a typed operand beside it, so
b * 2with abyte bcomputes at 8 bits; - attribute arguments.
- An integer literal can become a float (
float f = 5;). A float literal never becomes an integer. - Integer and float literals both become
decimal, built exactly from their digits:decimal r = 5 / 100;is0.05, computed in decimal at compile time. A literal thatdecimalcannot hold exactly is a compile error, and a literal written with themsuffix (1.5m) is adecimalthat adopts no other type (lang.numeric-literals). - A literal-only expression with a float literal in it and no context is a
float, sovar y = 1 / 2 + 0.5;is1.0. - A named constant (
const,static const) is a value, not a literal.float g = N / 3;withconst int NneedsN.toFloat(). - A literal-only expression is evaluated at compile time exactly as the run time would evaluate it in its type, operator by operator.
- A step whose result does not fit is a compile error that names the value and the range.
int16 h = 300 * 300;reportsliteral expression 90000 out of range for 'int16'. - Integer division or remainder by zero, and a shift count outside the width, are compile errors too.
- Float division by zero keeps its IEEE answer, so
1.0 / 0.0is infinity.
- A step whose result does not fit is a compile error that names the value and the range.
- A range with literal bounds adopts the element type:
Array<float> ys = [1..3];holds floats. A range with a variable bound has that bound's type. - A wide integer literal adopting a float converts from its own digits, never through a signed 64-bit overflow:
float f = 18446744073709551615;stores18446744073709551616.0.
Overload selection.
- A value argument chooses among overloads only through exact matches and lossless widenings, and an exact match wins.
- A literal argument prefers the overload of its own default type, so
f(1 / 3)withf(int)andf(float)callsf(int). Otherwise the literal goes to the parameter that holds it best. - Two overloads that tie on different numeric targets make the call ambiguous. The result never depends on declaration order. Convert the argument explicitly to choose.
f(1.5)withf(float)andf(decimal)callsf(float);f(1.5m)callsf(decimal). Anintorfloatvalue never selects adecimalparameter.
Examples
Boundaries, compound assignment and ranges:
Typed boundaries
use io::console;
float half(int n) => n.toFloat() / 2;
int whole(float f) => f.toInt();
void demo() {
int8 a = 5;
int x = a * 100;
console.writeln(x);
int total = 0;
total += a;
console.writeln(total);
console.writeln(half(5));
console.writeln(whole(3.99));
Array<float> fs = [1, 2];
Array<float> ys = [1..3];
console.writeln(fs);
console.writeln(ys);
float? opt = 4;
console.writeln(opt);
}
demo();
-12
5
2.5e0
3
[1.0e0, 2.0e0]
[1.0e0, 2.0e0, 3.0e0]
4.0e0
Overload selection, and string concatenation:
Overloads and string +
use io::console;
string pick(int x) => "int";
string pick(float x) => "float";
string size(int16 x) => "int16";
string size(float x) => "float";
console.writeln(pick(1));
console.writeln(pick(1 / 3));
console.writeln(pick(1.5));
byte b = 3;
console.writeln(size(b));
console.writeln("n=" + 5);
console.writeln(5 + "n");
console.writeln("x" + 1.5);
int
int
float
int16
n=5
5n
x1.5e0
Crossing into and out of decimal:
Explicit decimal conversions
use io::console;
string pick(float x) => "float";
string pick(decimal x) => "decimal";
void demo() {
int qty = 3;
decimal price = 19.99;
decimal total = price * qty.toDecimal();
console.writeln(total);
console.writeln(total.toInt());
console.writeln(total.toFloat());
float f = 0.1;
console.writeln(f.toDecimal() + 0.2);
console.writeln(pick(1.5));
console.writeln(pick(1.5m));
}
demo();
59.97
59
5.997e1
0.3
float
decimal
Notes
In the last example size(b) selects size(int16), because a byte widens to an int16 and does not cross into the floats.
See also
- Sized integers: byte, int8, int16, int32, uint — The fixed-width integer types, how arithmetic wraps, how mixed widths combine, and when conversions throw.
- Sized floats: float8, float16, float32 — The narrow floating-point formats, how every operation re-rounds, and where they overflow or throw.
- decimal — The exact base-10 number for money and other decimal quantities — 34 significant digits, a kept scale, value equality and half-even rounding.
- Numeric literals — Decimal, hexadecimal and binary integers, floats, the
msuffix of a decimal literal, and the_digit separator. - int — The signed 64-bit integer type, the default type of whole numbers.
- float — A 64-bit IEEE 754 floating-point number (binary64).
- decimal — An exact base-10 number: up to 34 significant digits and up to 34 digits after the point.