Math, Money & Time

Hale provides standard arithmetic and bitwise operators alongside first-class types for exact fixed-point decimals (Decimal), nanosecond time spans…

Hale provides standard arithmetic and bitwise operators alongside first-class types for exact fixed-point decimals (Decimal), nanosecond time spans (Duration), UTC timestamps (Time), and bounded or distinct integers. Financial calculations, unit conversions, and time arithmetic are checked at compile time with explicit rounding policies.

fn main() {
let unit_price: Decimal<2> = 19.99d;
let total = unit_price * 3d; // 59.97 (exact Decimal<2>)
let start = `2026-05-08T12:00:00Z`;
let deadline = start + 1h + 30min; // 2026-05-08T13:30:00Z
println(f"total={std::decimal::format(total, 2)} deadline={deadline}");
}

Numeric, Logical, and Bitwise Operators

Section titled “Numeric, Logical, and Bitwise Operators”
Category Operators Supported Types Behavior & Notes
Arithmetic +, -, *, / Int, U64, I32…U8, Float, Decimal, U256, I256, Duration (restricted) Integer / truncates toward zero; String also supports +; a fixed-width integer’s (U64, I32…U8) or a 256-bit integer’s overflow stops the process
Remainder % Int, U64, I32…U8, Decimal, U256, I256 Not defined on Float
Equality ==, != Int, U64, I32…U8, Float, Decimal, U256, I256, Bool, String, Duration, Time, enum, distinct Int Not defined on structs, tuples, or arrays (compare field by field)
Ordering <, <=, >, >= Int, U64, I32…U8, Float, Decimal, U256, I256, String, Duration, Time Does not chain; write a < b && b < c
Logical &&, ||, ! Bool && and || short-circuit
Bitwise &, |, ^, <<, >>, ~ Int, U64, I32…U8, U256, I256 Bitwise AND, OR, XOR, shifts (by an Int count), and NOT
let a = 7 + 3; // 10
let d = 7 / 3; // 2 (integer division)
let e = 7 % 3; // 1 (remainder)
let between = a > 0 && a < 100; // chained comparisons require &&
let safe = d != 0 && a / d > 2; // short-circuits before division when d == 0
let masked = (a << 2) & 0xFF; // bitwise operations on Int

Int, Float, and Decimal Overview

Section titled “Int, Float, and Decimal Overview”
Type Representation Implicit Conversions Primary Use Case
Int 64-bit signed integer (i64) Widens to Float in unambiguous contexts Counts, indices, bitwise logic
U64 64-bit unsigned integer, 0 to 2^64 - 1 None (U64::from_int(n)); an integer literal takes it from its place Hashes, counters past 2^63, uint64 IDs and protocol fields
I32, U32, I16, U16, I8, U8 32-, 16- and 8-bit signed and unsigned integers, stored at that width Widen where nothing is lost (U8 into U32, I32 into Int); narrow with T(x) or ... Dense buffers and records, vectorized kernels, binary protocols and C types
Float 64-bit IEEE-754 double (f64) None Scientific math, ratios, physical measurements
Decimal (Decimal<9>) 128-bit fixed-point, 9 fractional places Widens to Decimal<S> where S > 9 via .rescale(S) General exact decimal arithmetic
Decimal<S> (S in 0..=18) 128-bit fixed-point, S fractional places None (distinct per scale S) Currency (Decimal<2>), high-precision tokens (Decimal<18>)
U256 / I256 256-bit unsigned / two’s complement signed integer None (U256::from_int(n)) Chain values: balances, token amounts, ABI words, fixed-point prices

Int and Float Conversions and Math

Section titled “Int and Float Conversions and Math”

Implicit Widening and Explicit Casts

Section titled “Implicit Widening and Explicit Casts”

Hale automatically widens Int to Float in five unambiguous contexts:

  1. At a let binding with a : Float type annotation (let x: Float = n;).
  2. When passing an Int argument to a Float function parameter (std::math::sqrt(16)).
  3. In binary arithmetic or comparisons where the other operand is already Float (2.0 * 3).
  4. In a Float field of a type struct literal.
  5. When returning an Int from an infallible -> Float function (fn f(n: Int) -> Float { return n; }).

Where both operands are Int or when converting Float to Int, use the built-in Float(x) and Int(x) casts or their std::math equivalents:

let hits = 3;
let total = 8;
let rate = Float(hits) / Float(total); // 0.375 (widens before division)
let truncated = Int(3.9); // 3 (truncates toward zero)

Int(x) and Float(x) are the only primitive cast expressions in the language; type names like String(x), Bool(x), and Bytes(x) are not casts and are rejected at compile time. Neither cast takes a Decimal<S>: Int(d) is refused by hale check (a Decimal has no Int; d.rescale(0) or trunc is its whole part as a Decimal<0>, and Int(std::decimal::to_float(d)) its nearest Int through Float), and Float(d) points at std::decimal::to_float(d).

std::math Functions and IEEE-754 Semantics

Section titled “std::math Functions and IEEE-754 Semantics”
Function Signature Description
abs(x) (T) -> T (builtin) Absolute value (Int, Float, Decimal, Duration)
min(a, b) / max(a, b) (T, T) -> T (builtin) Minimum / maximum; returns NaN if either Float argument is NaN. T may also be a quantity or point type (min(100ms, lo) over two Millis, two Prices); both operands must be one type at one unit
std::math::int_to_float(n) (Int) -> Float Converts Int to Float (equivalent to Float(n))
std::math::float_to_int(x) (Float) -> Int Truncates Float toward zero (equivalent to Int(x))
std::math::round(x) (Float) -> Int Rounds half away from zero (2.5 -> 3, -2.5 -> -3)
std::math::trunc(x) (Float) -> Int Truncates toward zero to Int
std::math::floor(x) / ceil(x) (Float) -> Float Rounds down / up to nearest whole Float
std::math::sqrt(x) / pow(x, y) (Float, ...) -> Float Square root and exponentiation
std::math::exp(x) / log(x) (Float) -> Float Natural exponential and logarithm
std::math::nan() / is_nan(x) () -> Float / (Float) -> Bool Produces or tests IEEE-754 NaN

Float comparisons follow IEEE-754 rules:

Exact Fixed-Point Numbers (Decimal and Decimal<S>)

Section titled “Exact Fixed-Point Numbers (Decimal and Decimal<S>)”

Use Decimal for prices, balances, and financial quantities where binary floating-point drift (0.1 + 0.2 != 0.3) is unacceptable. Write Decimal literals with a d suffix:

let price: Decimal<2> = 19.99d;
let wei: Decimal<18> = 0.000000000000000001d;
let total = price * 3d; // 59.97 (Decimal<2>)

Scale Rules and .rescale(S)

Section titled “Scale Rules and .rescale(S)”
let precise: Decimal<18> = 1d / 3d; // 0.333333333333333333
let cents = precise.rescale(2) or half_even; // 0.33 (rounded)
let exact = precise.rescale(2) or raise; // fails if nonzero digits are dropped
let wide = cents.rescale(18); // exact widening, no `or` needed

Supported narrowing policies on .rescale(S) are or trunc, or floor, or ceil, or half_up, or half_even, or <fallback>, or raise, and or handler(err).

Formatting and Converting Decimal

Section titled “Formatting and Converting Decimal”

Printing a Decimal<S> trims trailing fractional zeros (12.50d prints as 12.5), serializes exact digits in JSON, and occupies 16 bytes on the bus regardless of scale.

Function Signature Description
std::decimal::format(d, places) (Decimal<S>, Int) -> String Formats with exact fractional places using half_up rounding
std::decimal::from_int(n) (Int) -> Decimal<9> Exact conversion from Int (chain .rescale(S) for other scales)
std::decimal::from_float(x) (Float) -> Decimal<9> fallible(...) Converts Float rounded half-away-from-zero at the 9th place; fails on NaN, Inf, or |x| > ~1.7e29
std::decimal::to_float(d) (Decimal<S>) -> Float Converts Decimal to closest IEEE-754 Float

Unsigned 64-bit Integers (U64)

Section titled “Unsigned 64-bit Integers (U64)”

U64 holds 0 through 2^64 - 1: a hash, a sequence number that runs past 2^63, an identifier or a protocol field another system hands out as a uint64. It is the same 8 bytes as an Int, read as unsigned. An integer literal is a U64 wherever its place is one, so there is no conversion to write for one:

fn fnv1a(text: String) -> U64 {
let bytes = std::bytes::from_string(text);
let mut h: U64 = 14695981039346656037; // a literal past Int's max
let mut i = 0;
while i < len(bytes) {
h = h ^ U64::from_int(std::bytes::read_u8(bytes, i) or 0);
h = U64::wrapping_mul(h, 1099511628211); // a hash wants wrapping
i = i + 1;
}
return h;
}
fn main() {
let seq: U64 = 18446744073709551615; // 2^64 - 1
let next = U64::checked_add(seq, 1) or 0; // overflow fails into the `or`
println(fnv1a("a"), " ", next, " ", seq / 2, " ", seq >> 60);
let n = U64::to_int(seq) or -1; // past Int's max: -1
let f = Float(seq); // the nearest double
}

Fixed-width Integers (I32, U32, I16, U16, I8, U8)

Section titled “Fixed-width Integers (I32, U32, I16, U16, I8, U8)”

Int is 64 bits everywhere. When a value has a known, smaller range (a byte of a frame, a pixel channel, a 16-bit sample, a 32-bit ID another system hands out) a fixed-width integer stores it at its own width: a bounded[U8; 1024] field is 1024 bytes, not 8192, and a loop over U32s works four lanes of a 128-bit vector register where an Int loop works two. I is signed, U unsigned; I32 holds -2147483648 through 2147483647, U8 0 through 255.

type Frame { kind: U8; samples: bounded[I16; 256]; }
fn checksum(f: Frame) -> U32 {
let mut h: U32 = 2166136261; // a literal takes its place's type
for s in f.samples {
h = U32::wrapping_mul(h ^ (U32(Int(s) & 0xFFFF) or 0), 16777619);
}
return h;
}
fn main() {
let mut f = Frame { kind: 3 };
push(f.samples, -32768) or discard;
push(f.samples, 1200) or discard;
let peak: Int = at(f.samples, 1) or 0; // an I16 widens into an Int
let level = U8(peak / 8) or clamp; // a narrowing says what happens outside 0..255
let total = U32::checked_add(checksum(f), 1) or 0; // overflow fails into the `or`
println(f.kind, " ", level, " ", total);
}

256-bit Integers (U256 and I256)

Section titled “256-bit Integers (U256 and I256)”

U256 (0 through 2^256 - 1) and I256 (-2^255 through 2^255 - 1) carry the values chain APIs speak in: balances, token amounts, ABI words, and the fixed-point numbers of AMM price math, all past the range of Decimal’s 128-bit mantissa. They have no literal; U256:: and I256:: functions make and take them:

fn quote(amount_in: U256, reserve_in: U256, reserve_out: U256) -> U256 fallible(ArithError) {
// a * b / c with the product exact in 512 bits: no overflow in between
return U256::mul_div(amount_in, reserve_out, reserve_in) or raise;
}
fn main() {
let wei = U256::parse("1000000000000000000") or raise; // decimal or 0x hex
let fee = U256::from_int(3);
let out = quote(wei, U256::from_int(5000), U256::from_int(7000)) or raise;
println(out, " ", U256::to_hex(wei * fee)); // 1400000000000000000 0x29a2241af62c0000
let bytes = U256::to_be_bytes(wei); // 32 big-endian bytes
let back = U256::from_be_bytes(bytes) or raise;
let small = U256::to_int(back / U256::from_int(1000000000)) or raise; // 1000000000
}

Duration and Time

Section titled “Duration and Time”

Duration and Time are defined by the standard library using Hale’s unit system: Duration is quantity Int in ns, and Time is point Duration (nanoseconds since the Unix epoch in UTC).

Time Units and std::time Reference

Section titled “Time Units and std::time Reference”
Unit / Function Definition / Signature Description
ns, us, ms, s, min, h, day 1us = 1000ns, 1ms = 1000us, 1s = 1000ms, 1min = 60s, 1h = 60min, 1day = 24h Duration literal suffixes (write 1h + 30min, never 1h30m, 5m, or 3d)
std::time::sleep(d) (Duration) -> () Sleeps for duration d
std::time::monotonic() () -> Duration Monotonic elapsed time since boot (never jumps backward; use for benchmarks/timers)
std::time::current() () -> Time Current UTC wall-clock instant (Time)
std::time::now() () -> Int Current UTC Unix timestamp in whole seconds (Int)
std::time::iso8601(t) (Time) -> String Formats Time as an ISO-8601 UTC string
std::time::parse_time(s) (String) -> Time fallible(ParseError) Parses an ISO-8601 UTC string (validates leap years and calendar dates)
std::time::parse_rfc3339(s) (String) -> Time fallible(ParseError) Parses an RFC 3339 timestamp with its offset (Z, +02:00, -05:30) and applies the offset: 2026-11-15T10:00:00+02:00 is 08:00:00Z
std::time::parse_iso8601(s) (String) -> Int fallible(ParseError) Parses an ISO-8601 string to Unix epoch seconds (Int), supporting dates outside 1677–2262
std::time::unix(t) / nanos(t) (Time) -> Int Extracts Unix seconds or epoch nanoseconds from Time
std::time::time_from_unix(secs) / from_nanos(n) (Int) -> Time Constructs Time from seconds or nanoseconds

Duration Arithmetic

Section titled “Duration Arithmetic”

Every Duration counts nanoseconds (println(16ms) outputs 16000000ns). Durations support addition, subtraction, comparison, and integer scaling:

let timeout = 5s;
let frame = 16ms;
let compound = 1h + 30min;
let backoff = tries * 100ms; // Int * Duration -> Duration
let slice = timeout / workers; // Duration / runtime Int -> Duration (integer division)
let half = timeout / 2 or floor; // Duration / literal Int -> requires rounding policy
let frames = timeout / frame; // Duration / Duration -> Int

Dividing a Duration by a compile-time integer literal requires an explicit remainder policy (or floor, or ceil, or trunc, or half_up, or half_even, or or <fallback>). Multiplying two durations (Duration * Duration) is a compile error.

Time Instants

Section titled “Time Instants”

Write Time literals as UTC ISO-8601 timestamps enclosed in backticks:

let launch = `2026-05-08T12:00:00Z`;
let precise = `2026-09-14T08:30:15.25Z`;
let deadline = launch + 30min;
let slack = deadline - std::time::current(); // Duration

Distinct Identities, Bounded Ranges, and Custom Units

Section titled “Distinct Identities, Bounded Ranges, and Custom Units”

Identities (distinct Int) and Ranges (range:)

Section titled “Identities (distinct Int) and Ranges (range:)”

Use distinct Int to create strongly typed integer IDs that cannot be added or mixed with plain Int, and { range: low..high; } to constrain valid integer bounds:

type OrderId = distinct Int;
type Byte = Int { range: 0..256; }
type Session = distinct Int { range: 0..64; }
fn main() {
let id: OrderId = 4;
let b: Byte = 200;
let total: Int = b + 55; // range types widen to Int automatically
let slot = Session(70) or 0; // 70 is out of range 0..64 -> substitutes 0
let top = Byte(total + 10) or clamp;
let raw: Int = Int(id); // explicit unwrap of distinct Int
println(id, " ", total, " ", slot, " ", top, " ", raw);
}

Narrowing an integer into a ranged type requires an or clause (or <fallback>, or clamp, or wrap, or handler(err), or or raise). Out-of-range literals (let b: Byte = 300;) fail at compile time.

Custom Units and Quantities

Section titled “Custom Units and Quantities”

You can declare domain-specific units (cents, dollars, basis points, bytes, ticks) with unit, quantity, and point:

unit cent;
unit USD = 100 cent;
unit pct = 1/100;
unit bp = 1/100 pct;
type Money = quantity Int in cent;
type Ledger = Money { round: half_even; }
type Rate = quantity Int in bp;
fn main() {
let fee = 1_250_000USD * 3bp; // exact: 375000000 Money in 1/10000 cent (375 USD)
let odd = 1_234_567USD * 3bp; // exact: 370.3701 USD in 1/10000 cent
let paid: Ledger = odd; // rounds via Ledger's half_even policy
let cents = odd.in(cent) or ceil; // explicit site-level rounding
println(fee, " ", odd, " ", paid, " ", cents);
}

See Units, End to End for the complete guide to custom units, affine points, unit splitting (.split(u)), and hale check --units.

Next: Units of Measure.