Skip to content

Numbers

Integer and floating types, literal forms, wrapping arithmetic, bit operations, conversions, and math methods.

int is a 64-bit signed integer and float is a 64-bit IEEE-754 double. Unsuffixed literals default to those two types, so most code never writes a width at all.

fn main() void {
    count := 42          // int
    ratio := 0.75        // float
    println("${count} items at ${ratio}")
}

int and i64 are one type, as are float and f64. The fixed-width spellings — i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32 — exist for binary, network, and FFI boundaries. byte is a spelling alias for u8.

Literals

Integer literals accept decimal, hex, octal, and binary bases, and _ may be used as a digit separator anywhere inside the number. A type suffix pins the literal to a specific width.

fn main() void {
    decimal := 1_000_000
    hex := 0xFF
    octal := 0o17
    binary := 0b1010

    mask: u32 = 0xFFFFu32
    precise: f32 = 1.25f32
    scientific := 1.5e3
    wide: i128 = 170141183460469231731687303715884105727

    println("${decimal} ${hex} ${octal} ${binary}")
    println("${mask} ${precise} ${scientific} ${wide}")
}

An annotated binding also fixes the width, so mask: u32 = 0xFFFF and mask := 0xFFFFu32 mean the same thing. A literal that does not fit its target width is rejected at check time:

fn too_wide() u8 {
    return 300u8
}

Watch the interaction between - and a suffix: -128i8 parses as the negation of the literal 128i8, and 128 does not fit in i8.

fn min_i8() i8 {
    return -128i8
}

Reach the extreme through a wrapping step instead:

fn min_i8() i8 {
    return (-127i8).wrapping_sub(1i8)
}

fn main() void {
    println("${min_i8()}")
}

Arithmetic wraps by default

+, -, and * wrap to the destination width rather than aborting. wrapping_add, wrapping_sub, and wrapping_mul are the explicit spellings of exactly that behaviour — reach for them when wrapping is the intent rather than the fallback.

fn main() void {
    counter: u8 = 250u8
    println("${counter + 10u8}")                // 4 — the operator wraps
    println("${counter.wrapping_add(10u8)}")    // 4 — same result, stated
    println("${counter.wrapping_sub(255u8)}")   // 251
    println("${counter.wrapping_mul(3u8)}")     // 238
}

Arithmetic over literals alone is the exception: it is computed when the program is checked, and an operation that does not fit its type is refused there, as a literal that does not fit is. 250u8 + 10u8 is a compile-time error; 250u8.wrapping_add(10u8) is 4.

When overflow means the input was wrong, range-check before the arithmetic. The guard is a plain comparison, and the failure becomes a typed error:

error QuoteError { Overflow }

const MAX_LINE_TOTAL: int = 1_000_000_000

fn line_total(unit_price int, quantity int) int ! QuoteError {
    if unit_price < 0 || quantity < 0 { error Overflow }
    if quantity != 0 && unit_price > MAX_LINE_TOTAL / quantity { error Overflow }
    return unit_price * quantity
}

fn main() void {
    match line_total(1999, 3) {
        Ok(total) => println("${total}")
        Err(e) => println("overflow")
    }
    match line_total(999_999_999, 99) {
        Ok(total) => println("${total}")
        Err(e) => println("overflow")
    }
}

Division and remainder

Integer / truncates toward zero and % returns the matching remainder, so the remainder carries the sign of the dividend. Division by zero is the one integer operation with no defined answer — guard the divisor.

error MathError { DivideByZero }

fn ratio(numerator int, denominator int) int ! MathError {
    if denominator == 0 { error DivideByZero }
    return numerator / denominator
}

fn main() void {
    println("${7 / 2} ${-7 / 2} ${7 % 2} ${-7 % 2}")   // 3 -3 1 -1
    match ratio(7, 0) {
        Ok(v) => println("${v}")
        Err(e) => println("undefined")
    }
}

Euclidean division

% carries the sign of the dividend, so (-1) % 7 is -1. That is what the operator means, and it is the wrong answer for a hash bucket, a ring buffer index, a wrapped angle or a calendar day — all of which want a remainder in [0, |rhs|).

fn bucket(key int, buckets int) int {
    return key.rem_euclid(buckets)
}

fn main() void {
    println("${(-1) % 7} ${(-1).rem_euclid(7)}")        // -1 6
    println("${(-8).div_euclid(7)} ${(-8).rem_euclid(7)}")   // -2 6
    println("${bucket(-13, 8)}")
}

div_euclid is the quotient that makes it hold: self == q * rhs + r for every pair of signs, with r never negative. Both trap on a zero divisor, and on int.MIN by -1, exactly as / and % do.

Bit operations

Every integer width implements BitAnd, BitOr, BitXor, BitNot, Shl, and Shr, spelled &, |, ^, ~, <<, and >>. Shifts on signed types are arithmetic; on unsigned types they are logical.

fn main() void {
    a := 0b1100
    b := 0b1010
    println("${a & b}")      // 8   — 0b1000
    println("${a | b}")      // 14  — 0b1110
    println("${a ^ b}")      // 6   — 0b0110
    println("${~a}")         // -13 — two's complement
    println("${a << 2}")     // 48
    println("${a >> 2}")     // 3
}

A flag set is the idiomatic use. Keep the flag constants in one integer type and combine them with |; clear with & ~; toggle with ^.

const READ: int = 0b001
const WRITE: int = 0b010
const EXEC: int = 0b100

fn has(flags int, bit int) bool => (flags & bit) != 0

fn describe(flags int) string {
    mut out := ""
    if has(flags, READ) { out += "r" }
    if has(flags, WRITE) { out += "w" }
    if has(flags, EXEC) { out += "x" }
    return if out.is_empty() { "-" } else { out }
}

fn main() void {
    all := READ | WRITE | EXEC
    println(describe(all))            // rwx
    println(describe(all & ~WRITE))   // rx
    println(describe(all ^ READ))     // wx
    println(describe(0))              // -
}

Mixing widths in one bitwise expression is a type error, exactly as it is for +. Convert first:

fn mix(a u32, b int) u32 {
    return a & b
}

Byte order

wasm has no byte-swap instruction and every wire format needs one, so the family is written out on int, u16, u32 and u64.

fn main() void {
    v: u32 = 0x12345678u32
    println("${v.swap_bytes()}")
    println("${v.to_be().from_be() == v}")
}
Method Answers
swap_bytes() the bytes in the opposite order
to_be() / from_be() the swap — big-endian is not this target’s order
to_le() / from_le() the value unchanged

wasm is little-endian on every target — the specification says so rather than the platform — so to_le and from_le are the identity. They are still worth writing: a codec that says to_be where it means big-endian reads correctly whatever a future target does, and one that leaves the no-op out reads as if the question had not been asked.

Four integer functions

fn main() void {
    println("${(48).gcd(18)}")                    // 6
    println("${(1023).ilog2()}")                  // 9 — the floor
    println("${(145).isqrt() ?? -1}")             // 12 — the floor
    println("${(4).midpoint(7)}")                 // 5
}

isqrt answers int?: None for a negative, where the answer does not exist, rather than a sentinel a caller might use by accident. ilog2, ilog10 and ilog(base) stop the program for a value that is not above zero, as Rust’s do, and checked_ilog2, checked_ilog10 and checked_ilog answer None there instead. midpoint is the average that cannot overflow: (a + b) / 2 does, and int.MAX.midpoint(int.MAX) does not.

gcd is sign-blind and gcd(0, 0) is 0. The one pair whose answer is not representable is int.MIN.gcd(0), whose magnitude is 2^63.

Rounding division, signs and powers of two

Every integer width has these, as Rust’s integers do:

fn main() void {
    println("${(7).div_ceil(2)} ${(-7).div_ceil(2)}")        // 4 -3
    println("${(-7i32).div_euclid(2i32)} ${(-7i32).rem_euclid(2i32)}")  // -4 1
    println("${(-128i8).wrapping_div(-1i8)} ${(-128i8).wrapping_rem(-1i8)}")  // -128 0
    println("${(64u32).is_power_of_two()} ${(-5i16).signum()}")  // true -1
    println("${(999u32).ilog10()} ${(80u8).ilog(3u8)}")       // 2 3
}

div_ceil, div_euclid and rem_euclid stop the program where / and % do: on a zero divisor, and on MIN by -1. wrapping_div and wrapping_rem answer that one quotient that leaves the type by wrapping. signum is a signed width’s.

Conversions

Every integer type carries to_* methods for every other width. They are wrapping conversions: narrowing keeps the low bits, and signed/unsigned conversions of the same width reinterpret the bit pattern.

fn main() void {
    value := 300
    println("${value.to_u8()}")       // 44 — low byte
    println("${7i8.to_int()}")        // 7
    println("${value.to_float()}")    // 300
    println("${value.to_u32()}")
    println("${value.to_usize()}")
    println("${2.9.to_int()}")        // 2 — truncates toward zero
}

u8(value) and float(value) are cast-expression spellings of the same operation, so value.to_u8() and u8(value) agree.

Because the to_* family truncates silently, a boundary that must reject out-of-range values needs its own range check:

error HeaderError { FieldTooLarge { value: int } }

fn encode_length(value int) u16 ! HeaderError {
    if value < 0 || value > 65_535 { error FieldTooLarge { value: value } }
    return value.to_u16()
}

fn main() void {
    match encode_length(1200) {
        Ok(n) => println("${n}")
        Err(e) => println("too large")
    }
    match encode_length(70_000) {
        Ok(n) => println("${n}")
        Err(e) => println("too large")
    }
}

Integer-to-float conversion can lose precision above 2^53. Float-to-integer conversion truncates toward zero, and float.to_f32 can lose both precision and range.

Bounds

min, max, clamp and abs are available on integers and floats.

(This paragraph said clamp was “declared but has no lowering path — compose it from max and min”. It lowers, and is written as exactly that composition in stdlib/int.at.)

fn clamp_percent(raw int) int {
    return raw.clamp(0, 100)
}

fn spread(a int, b int) int {
    return (a - b).abs()
}

fn main() void {
    println("${clamp_percent(140)} ${clamp_percent(-3)} ${clamp_percent(42)}")
    println("${spread(4, 9)}")
}

The pointer-width pair

usize is the type every collection index in this library is; a length (len()) is an int, so arithmetic on it cannot wrap below zero. It has min, max, clamp and pow, and the checked, wrapping and saturating forms as well:

fn room_for(have usize, want usize) usize {
    return want.saturating_sub(have)
}

fn main() void {
    a: usize = 7
    println("${a.clamp(1, 5)} ${room_for(9, 4)} ${a.pow(2)}")
    println("${match a.checked_sub(9) { Some(v) => v.to_int() None => -1 }}")
}

isize gets the same surface, including the overflow forms, and both types have MIN and MAX.

Both are 64 bits, on every target. A usize is one Atoll pointer wide, and an Atoll pointer is 64 bits on wasm32 as well as wasm64 — the machine’s address width and a pointer’s width are different questions here. So usize.MAX is 2^64 - 1 and isize.MIN is the same value int.MIN is, and a program can rely on that rather than converting through int to find out which width it got.

fn main() void {
    println("${usize.MAX} ${isize.MAX}")
    println("${(3).to_isize().saturating_sub(isize.MIN)}")
}

An earlier version of this page said the bound was “a fact about the target” and that neither type could have one. That was wrong, and it was the stated reason isize had no overflow forms.

Floating point

ceil, floor, trunc, and round all answer a float — they move a value to a whole number, they do not change its type. to_int is the narrowing, and it is written where it happens. round goes half away from zero; trunc is the one that goes toward zero.

fn rounding(x float) string {
    up: int = x.ceil().to_int()
    down: int = x.floor().to_int()
    nearest: int = x.round().to_int()
    toward_zero: int = x.trunc().to_int()
    return "${up} ${down} ${nearest} ${toward_zero}"
}

fn main() void {
    println(rounding(2.5))    // 3 2 3
    println(rounding(-2.5))   // -2 -3 -3
}

Rounding to a number of decimal places is round_to in the stdlib. Ties go away from zero, so (2.5).round_to(0) is 3.

fn main() void {
    println("${(3.14159).round_to(2)}")    // 3.14
    println("${(2.71828).round_to(3)}")    // 2.718
    println("${(2.5).round_to(0)}")        // 3
}

A float prints in its shortest form that reads back as the same value, so a whole float prints with no point — 300, 3 — and 0.1 + 0.2 prints 0.30000000000000004. round_to changes the value, not how it is written: (546.5).round_to(2) still prints 546.5. To write a fixed number of decimals, use to_fixed(places), which renders every place. It rounds the exact binary value of the float to nearest, ties to even, as Rust’s format!("{:.2}", x) does, so a decimal that is not exact in binary rounds by what it really is: 1.005 is a hair below, and two places give 1.00. write_fixed(places, out) appends the same digits to a string you own.

fn main() void {
    println((546.5).to_fixed(2))       // 546.50
    println((2.5).to_fixed(0))         // 2
    println((0.125).to_fixed(2))       // 0.12
    println((1.005).to_fixed(2))       // 1.00
    println((0.1 + 0.2).to_fixed(2))   // 0.30
}

The math surface is sqrt, cbrt, pow, abs, sign, exp, log, log2, log10, sin, cos, tan, asin, acos, and atan. All take and return float; angles are radians.

struct Vec2 { x float, y float }

fn Vec2.magnitude(&self) float {
    return (self.x * self.x + self.y * self.y).sqrt()
}

fn Vec2.normalized(&self) Vec2 {
    m := self.magnitude()
    if m == 0.0 { return Vec2 { x: 0.0, y: 0.0 } }
    return Vec2 { x: self.x / m, y: self.y / m }
}

fn Vec2.rotated(&self, radians float) Vec2 {
    c := radians.cos()
    s := radians.sin()
    return Vec2 { x: self.x * c - self.y * s, y: self.x * s + self.y * c }
}

fn main() void {
    v := Vec2 { x: 3.0, y: 4.0 }
    println("${v.magnitude()}")           // 5
    println("${v.normalized().x}")        // 0.6
    println("${v.rotated(1.0).y}")
    println("${(8.0).cbrt()} ${(2.0).pow(10.0)} ${(8.0).log2()}")
}

atan2 is a method: y.atan2(x). Written as a static, float.atan2(y, x), it is ATOLL3012, one argument too many.

Constants

π and τ are associated constants, beside the trigonometric calls that need them.

fn circumference(radius float) float {
    return float.TAU * radius
}

fn main() void {
    println("${circumference(1.0)}")
    println("${float.PI.to_degrees()}")          // 180
    println("${(180.0).to_radians() == float.PI}")
}

PI, TAU, E, SQRT_2, LN_2, LN_10, LOG2_E, LOG10_E, LOG2_10, LOG10_2, FRAC_PI_2, FRAC_PI_3, FRAC_PI_4, FRAC_PI_6, FRAC_PI_8, FRAC_1_PI, FRAC_2_PI, FRAC_1_SQRT_2 and FRAC_2_SQRT_PI, each the shortest decimal that reads back to the same double — so float.PI.to_string().to_float() == float.PI, and a guest constant agrees with a host sin in the last place.

to_degrees() and to_radians() are one multiplication each.

NaN and infinity

Floating division by zero produces an IEEE infinity, and domain errors such as the square root of a negative produce NaN. Neither is a typed error, so code that must reject them has to test for them. is_nan and is_finite are the two classification predicates that lower; is_infinite and is_normal do not, and !x.is_finite() covers the first of them.

fn safe_ratio(numerator float, denominator float) float? {
    result := numerator / denominator
    if result.is_finite() { return Some(result) }
    return None
}

fn classify(x float) string {
    if x.is_nan() { return "nan" }
    if !x.is_finite() { return "infinite" }
    if x == 0.0 { return "zero" }
    return "finite"
}

fn main() void {
    println(classify(1.0 / 0.0))              // infinite
    println(classify((0.0 - 1.0).sqrt()))     // nan
    println("${safe_ratio(1.0, 0.0) ?? -1.0}")
    println("${safe_ratio(1.0, 4.0) ?? -1.0}")
}

Ordinary comparison follows IEEE, where NaN is unordered — x < y, x > y, and x == y are all false when either side is NaN. That also means a NaN used as a Map key can never be looked up again. The operators stay IEEE’s in generic code too: a < b over a type parameter that is a float is the same comparison. partial_compare answers that order as an Ordering?, None when either side is NaN, as Rust’s partial_cmp.

Ordering through Comparable (sorted, min, max and compare_to) is total_compare: IEEE-754 total order, as Rust’s total_cmp, so a sort with a NaN in it is deterministic, -0.0 sorts before 0.0, a NaN with its sign bit set sorts before negative infinity and any other NaN after infinity. Filter NaN out first when it should not be in the answer.

fn sorted_finite(values []float) []float {
    return values.filter(v => v.is_finite()).collect().sorted()
}

fn main() void {
    for v in sorted_finite([3.0, 1.0 / 0.0, 1.0, 2.0]) {
        println("${v}")
    }
}

Parsing and formatting

Parsing answers a Result and never panics. int.from_string and float.from_string are the static forms; string.to_int and string.to_float are the method forms, and they are the same operation. The error says why the text is not a number (ParseIntError: Empty, InvalidDigit, Overflow; ParseFloatError: Empty, InvalidDigit), and .ok() is the Option for a caller that only wants the number.

error ConfigError { NotANumber { key: string } }

fn read_port(raw string) int ! ConfigError {
    match int.from_string(raw.trim()) {
        Ok(port) => return port
        Err(_) => error NotANumber { key: "port" }
    }
}

fn read_timeout(raw string) int {
    return raw.trim().to_int().ok() ?? 30
}

fn main() void {
    match read_port(" 8080 ") {
        Ok(p) => println("port ${p}")
        Err(e) => println("bad port")
    }
    println("${read_timeout("junk")}")     // 30
    println("${"4.25".to_float().ok() ?? 0.0}")
}

Parsing rejects leading or trailing junk and out-of-range values, so "12abc" is Err(InvalidDigit) and "99999999999999999999" is Err(Overflow).

Formatting goes the other way with to_string, which every numeric type implements. String interpolation calls it for you, so "${x}" and x.to_string() produce the same text.

fn main() void {
    n := 1999
    println("${n} == ${n.to_string()}")
    println("${(0.5).to_string()}")
}

to_radix(base) is the stdlib’s non-decimal formatter. Bases outside 2–36 answer the empty string.

fn main() void {
    println("${(255).to_radix(16)}")         // ff
    println("${(0b1011).to_radix(2)}")       // 1011
    println("${(9).to_radix(1)}")            // empty — base out of range
}

The low-level write_decimal methods write decimal ASCII into caller-reserved byte storage. They back Buffer.append_int and Buffer.append_float; prefer those (see Bytes) over calling write_decimal yourself.

fn main() void {
    mut line: []byte = []
    line.append_string("count=")
    line.append_int(42)
    println(string.from_utf8(line).ok() ?? "")
}

Generic numeric code

Arithmetic is available generically through the Numeric trait, which supplies add, sub, mul, div, to_int, and to_float. There is no Add trait.

fn total[T: Numeric](values []T, zero T) T where T: Clone {
    mut acc := zero
    for v in values {
        acc = acc.add(v.clone())
    }
    return acc
}

fn main() void {
    println("${total([1, 2, 3], 0)} ${total([1.5, 2.5], 0.0)}")
}

Comparable[T], Equatable, and Hashable are implemented for every numeric type, so numbers work as Map keys, sort keys, and min/max arguments without any extra declaration.

fn spread(values []int) int {
    hi := values.max() ?? 0
    lo := values.min() ?? 0
    return hi - lo
}

fn main() void {
    println("${spread([4, 9, 1, 7])}")
}

A worked example

A latency histogram: parsing at the boundary, integer comparison for bucketing, and float math only for the reported average.

struct Bucket { label string, count int }

fn bucket_for(latency_ms int) string {
    if latency_ms < 10 { return "<10ms" }
    if latency_ms < 100 { return "<100ms" }
    if latency_ms < 1000 { return "<1s" }
    return ">=1s"
}

fn parse_samples(raw []string) []int {
    return raw.map(s => s.trim().to_int().ok() ?? -1).filter(v => v >= 0).collect()
}

fn summarize(samples &[]int) []Bucket {
    labels := ["<10ms", "<100ms", "<1s", ">=1s"]
    mut buckets: []Bucket = []
    for label in labels {
        n := samples.count(v => bucket_for(v) == label)
        if n > 0 { buckets.push(Bucket { label: label.clone(), count: n }) }
    }
    return buckets
}

fn mean(samples &[]int) float {
    if samples.is_empty() { return 0.0 }
    return samples.sum().to_float() / samples.len().to_float()
}

fn main() void {
    samples := parse_samples(["4", "42", "900", "1500", "not-a-number"])
    for b in summarize(samples) {
        println("${b.label}: ${b.count}")
    }
    println("mean ${mean(samples)}ms over ${samples.len()} samples")
    println("p-max ${samples.max() ?? 0}ms")
}

Choosing a type

Use int for counts, application-level indexes, and database integers. Use usize for layout sizes and pointer arithmetic, and never expose a pointer-sized width in a file or wire format — pick an explicit u32/u64 there instead. Use fixed widths at binary, network, and FFI boundaries, and float unless a protocol specifically calls for f32.

Binary floating point is not a decimal money type. Money is decimal, an exact base-ten number that keeps the scale it is written at:

fn main() int {
    total: decimal = 19.99 + 5.01
    println("${total}")    // 25.00
    return 0
}

planned marks a design not built yet: neither compiler has decimal yet. Until one does, hold fixed-scale values as an integer count of minor units:

struct Money { cents int }

fn Money.plus(&self, other Money) Money => Money { cents: self.cents + other.cents }

fn Money.to_string(&self) string {
    whole := self.cents / 100
    fraction := (self.cents % 100).abs()
    pad := if fraction < 10 { "0" } else { "" }
    return "${whole}.${pad}${fraction}"
}

fn main() void {
    total := Money { cents: 1999 }.plus(Money { cents: 501 })
    println(total.to_string())    // 25.00
}

Availability

Everything on this page compiles and runs: checked_*, wrapping_*, saturating_*, clamp, pow, try_to_*, to_radix, round_to, to_fixed, total_compare, is_infinite, is_normal, and the associated constants (int.MAX, float.PI). atoll doc --std int and atoll doc --std float list every method.

What is absent:

Signature What to know
to_char() on int not declared — ATOLL2003. char.from_u32(n.to_u32()) is the route.
float.atan2 a method, not a static: write y.atan2(x). float.atan2(y, x) is ATOLL3012, one argument too many.

Verified behaviour

fn main() int {
    return 85 / 2 + 85 % 2
}
fn main() int {
    f: float = 21.0 * 2.0
    return int(f)
}
fn main() int {
    a: i128 = 21
    b: i128 = a * 2
    return int(b)
}
fn main() int {
    masked: int = (40 | 2) & 63      // 42
    shifted: int = 21 << 1           // 42
    return masked + shifted - 42
}

Known gaps

  • truncate is spelled trunc — float.trunc() / f32.trunc(). Toward zero; round is half away from zero.
  • A width-changing cast between sized integers — i64(some_i32) — is refused. Convert through int.

Type to search…

↑↓ navigate↵ selectEsc close