Numeric and time
Math helpers, random numbers, dates and durations, backed by std/numeric and std/time.
Math basics
Most numeric operations are methods on the value itself: x.sqrt(), n.abs(), a.max(b). They need no import. What is left over (the constants,
and the two-argument functions with no natural receiver) is a set of free
functions in std/numeric/math, reached by binding the module with use std::numeric::math;.
A numeric literal receiver needs parentheses: (2.0).sqrt(), not 2.0.sqrt().
use std::numeric::math;
fn main() : i32 {
let pi : f64 = math::pi(); // 3.141592653589793
let e : f64 = math::e(); // 2.718281828459045
let s : f64 = (2.0).sqrt(); // 1.4142…
let p : f64 = (2.0).pow(10.0); // 1024.0
let c : f64 = (27.0).cbrt(); // 3.0
let h : f64 = math::hypot(3.0, 4.0); // 5.0
println((pi + e + s + p + c + h).toString());
return 0;
} The method surface, by receiver type
Each row lists the methods a receiver answers. Every f64 method has an f32 twin with the same name, returning f32.
| Receiver | Methods |
|---|---|
f64 | abs min max pow sqrt cbrt exp ln log2 log10 sin cos tan asin acos atan sinh cosh tanh floor ceil trunc sign isNaN isFinite isInfinite toString |
f64 to i64 | round truncToInt floorToInt ceilToInt |
i32 | abs absChecked min max toHex toBin toOct toString |
i64 | abs absChecked min max toHex toBin toString |
u8 u16 u32 u64 | min max toHex toBin toString (no abs: an unsigned value has no sign to strip) |
bool | toString |
char | toI32 toString isDigit isWhitespace toUpperCase toLowerCase |
string | toI32 toI64 toF64 toBool (parse; each throws ParseException) |
f64 rounding comes in two shapes. floor, ceil and trunc stay in the f64 domain. round, truncToInt, floorToInt and ceilToInt produce an i64. The same is true of f32. The as cast to an integer truncates toward
zero, like truncToInt.
Free functions in std/numeric/math
| Group | Free functions |
|---|---|
| Constants | pi(), e(), tau() |
| Two-argument | atan2(y, x), hypot(x, y) |
| Pair result | sinCos(x) returns both sine and cosine as a tuple |
| Integer bounds | i32Min(), i32Max(), i64Min(), i64Max(), u32Max(), u64Max() |
| Float bounds and special values | f64Min(), f64Max(), f64PositiveInfinity(), f64NegativeInfinity(), f64NotANumber() |
i32Max() is the largest value an i32 can hold. a.max(b) is the larger
of two numbers. The two share a word and nothing else.
Calling style
An operation on a value is a method on that value:
fn main() : i32 {
let r : f64 = (2.0).sqrt();
println(r.toString());
return 0;
} Methods on primitives need no use line at all.
Integer absolute value, two flavours
fn main() : i32 ! ArithmeticException {
let a : i32 = (-5).abs(); // 5; wraps on the i32 minimum
let b : i32 = (-5).absChecked(); // 5; throws on the i32 minimum
println((a + b).toString());
return 0;
} abs() of the minimum i32 returns it unchanged, the two’s-complement edge
case. absChecked() throws ArithmeticException instead. Use it when silent
overflow is not acceptable. Both exist on i64 too.
Attention: the receiver’s width picks the overload A literal receiver is an
i32, so(1).max(big)withbig : i64does not type-check: the argument would have to narrow. Write(1 as i64).max(big), or make the receiver ani64local.
NaN and infinity
fn main() : i32 {
let x : f64 = (-1.0).sqrt(); // NaN
if (x.isNaN()) {
// NaN propagates through every arithmetic op
}
if ((1000.0).exp().isInfinite()) { /* … */ }
return 0;
} Float / and % follow IEEE-754, so 1.0 / 0.0 is +Inf and 0.0 / 0.0 is NaN: neither aborts nor is rejected at compile time. (An integer 1 / 0 is
still rejected.)
NaN-aware code should classify before comparing. x == x is false for NaN,
so the usual == can mislead.
sign(x) is float-typed
fn main() : i32 {
let s : f64 = (-3.5).sign(); // -1.0
let z : f64 = (0.0).sign(); // 0.0
let n : f64 = (-1.0).sqrt().sign(); // NaN in, NaN out
println((s + z + n).toString());
return 0;
} The result stays a float, so you can fold the sign into a computation without a branch.
Random numbers
use std::numeric::random::Random;
fn main() : i32 {
Random::seed(42); // deterministic from here on
let a : i32 = Random::nextI32(); // uniform i32
let b : i64 = Random::nextI64();
let f : f64 = Random::nextF64(); // [0.0, 1.0)
let p : bool = Random::nextBool();
let dice : i32 = Random::nextRangeI32(1, 7); // [1, 7): that is 1 to 6
let big : i64 = Random::nextRangeI64(0, 1000000);
return dice;
} Random member | Returns | Range |
|---|---|---|
seed(s) | void | reseeds the shared stream |
nextI32() / nextI64() | integer | full range of the type |
nextF64() | f64 | [0.0, 1.0) |
nextBool() | bool | fair coin |
nextRangeI32(min, max) / nextRangeI64(min, max) | integer | [min, max); max <= min yields min |
All draws come from one process-wide xoshiro256** stream. Random is a
static facade over it, and the module’s functions reach the same stream, so random::nextI64() after use std::numeric::random; draws from the same
sequence. For deterministic tests, call seed with a fixed value. Left
unseeded, the stream seeds itself on first use from the operating system’s random generator (falling back to the wall clock).
Attention The stream is fast and reproducible, not cryptographic. Do not use it for tokens or keys an attacker must not guess.
Picking a random list element
use std::collections::ArrayList;
fn pickRandom(items : ArrayList<string>) : string
! IndexOutOfBoundsException
{
if (items.isEmpty()) {
throw IndexOutOfBoundsException("pickRandom: empty list");
}
let i : i64 = Random::nextRangeI64(0, items.size());
return items.get(i) ?? ""; // in range: never null here
} Time: wall clock and monotonic clock
fn main() : i32 {
let nowMs : i64 = now(); // Unix epoch milliseconds
let nowNs : i64 = nanoTime(); // monotonic nanoseconds, not wall-clock
println(nowMs.toString() + " " + nowNs.toString());
return 0;
} now() and nanoTime() are in the prelude, so no use line is needed. Use now() for “what date is it” and nanoTime() for “how long did this take”.
They are different counters with different guarantees.
Measuring elapsed time
fn doWork() : void {
}
fn timeIt() : i64 {
let start : i64 = nanoTime();
doWork();
let end : i64 = nanoTime();
return end - start; // nanoseconds elapsed
} nanoTime is monotonic: it never goes backward and is immune to clock
adjustments. Use it for benchmarks and timeouts.
Dates: LocalDateTime
LocalDateTime is a calendar date and time. All of its calendar arithmetic
is in UTC; the library has no time-zone database.
use std::time::datetime::LocalDateTime;
fn main() : i32 {
let dt : LocalDateTime = LocalDateTime::now();
let y : i32 = dt.getYear();
let m : i32 = dt.getMonth(); // 1..12
let d : i32 = dt.getDay(); // 1..31
let h : i32 = dt.getHour(); // 0..23
let mi : i32 = dt.getMinute(); // 0..59
let s : i32 = dt.getSecond(); // 0..59
return y;
} From a timestamp
use std::time::datetime::LocalDateTime;
fn main() : i32 {
let dt : LocalDateTime = LocalDateTime::fromMillis(1715342400000);
println(dt.formatIso());
return 0;
} Building explicitly
use std::time::datetime::LocalDateTime;
fn main() : i32 {
let dt : LocalDateTime = LocalDateTime::fromComponents(
2026, 5, 10, // year, month, day
14, 23, 45 // hour, minute, second
);
println(dt.formatIso());
return 0;
} Formatting
use std::time::datetime;
fn main() : i32 {
let ms : i64 = now();
let iso : string = datetime::formatIso8601(ms); // "2026-05-10T14:23:45.123Z"
let d : string = datetime::formatDate(ms); // "2026-05-10"
let t : string = datetime::formatTime(ms); // "14:23:45"
let http: string = datetime::formatHttpDate(ms); // "Sun, 10 May 2026 14:23:45 GMT"
println(iso + d + t + http);
return 0;
} Parsing ISO-8601
use std::time::datetime;
use std::lang::ParseException;
fn parseTimestamp(s : string) : i64 ! ParseException {
return datetime::parseIso8601(s); // returns epoch milliseconds
} Date arithmetic
A LocalDateTime is immutable. The plus* methods return a new value and
leave the receiver alone, so they chain:
use std::time::datetime::LocalDateTime;
fn main() : i32 {
let start : LocalDateTime = LocalDateTime::fromComponents(2026, 5, 10, 14, 0, 0);
let later : LocalDateTime = start.plusDays(3).plusHours(6); // 2026-05-13 20:00
println(later.formatIso()); // "2026-05-13T20:00:00.000Z"
return 0;
} LocalDateTime method | Returns | Effect |
|---|---|---|
plusDays(n) | LocalDateTime | add n days (n is an i32) |
plusHours(n) / plusMinutes(n) / plusSeconds(n) | LocalDateTime | add a time offset |
toMillis() | i64 | epoch milliseconds of this instant |
formatIso() | string | ISO-8601 text |
getYear() … getSecond() | i32 | calendar and clock fields, UTC |
To measure a span, subtract two toMillis() values and convert the raw
millisecond delta with std/time. Bind the module as use std::time;. Its
functions are top-level, not nested under a time::time path:
use std::time;
use std::time::datetime::LocalDateTime;
fn hoursBetween(a : LocalDateTime, b : LocalDateTime) : i64 {
let deltaMs : i64 = b.toMillis() - a.toMillis();
return time::durationToHours(deltaMs); // truncated toward zero
} Durations in std/time
std/time also builds durations from a unit. A duration is a count of milliseconds, so it adds straight onto an epoch timestamp:
use std::time;
fn main() : i32 {
let twoHours : i64 = time::durationFromHours(2); // 7_200_000 ms
let secs : i64 = time::durationToSeconds(twoHours); // 7200
println(twoHours.toString() + " " + secs.toString());
return 0;
} | Function | Effect |
|---|---|
durationFromSeconds(n) / durationFromMinutes(n) / durationFromHours(n) | a duration of n units, in milliseconds |
durationToSeconds(ms) / durationToMinutes(ms) / durationToHours(ms) | a millisecond duration, converted to that unit (truncated) |
instantNow() | the current epoch instant in milliseconds |
instantPlusMillis(t, ms) / instantMinusMillis(t, ms) | shift an epoch-millisecond instant |
instantUntil(start, end) | milliseconds from start to end |
monotonicNanos() | the monotonic clock in nanoseconds, as nanoTime() |
Decomposing an epoch timestamp
use std::time::datetime;
fn fields(ms : i64) : i32 {
let y : i32 = datetime::yearOf(ms);
let m : i32 = datetime::monthOf(ms);
let d : i32 = datetime::dayOf(ms);
let h : i32 = datetime::hourOf(ms);
let mi : i32 = datetime::minuteOf(ms);
let s : i32 = datetime::secondOf(ms);
let ms3 : i32 = datetime::millisecondOf(ms);
let dow: i32 = datetime::dayOfWeek(ms); // 0 = Sunday … 6 = Saturday
return y;
} For one-off field extraction, the free functions are cheaper than building a LocalDateTime. monthOf is 1-based and dayOfWeek is 0 for Sunday.
Sleeping
fn doWork() : void {
}
fn rateLimited() : void {
doWork();
sleep(1000); // 1 second
} sleep(ms) has millisecond resolution. A task that calls it parks on a timer
until the delay elapses, so the other tasks of its carrier run meanwhile.
Outside any task (in main, or in a Thread::run body) it pauses the calling
thread. An async fn may not call it (E0767). An async fn waits on the
timer its event loop interleaves instead: await Async::sleep(ms). See Tasks and async.
For sub-millisecond delays, a nanoTime busy-wait is the only option. It is
rare, and usually a sign the algorithm needs another shape.
Timeout pattern
fn check() : bool {
return true;
}
fn pollUntil(deadlineMs : i64) : bool {
while (now() < deadlineMs) {
if (check()) { return true; }
sleep(50);
}
return false;
}
fn main() : i32 {
let deadline : i64 = now() + 5000; // 5-second deadline
let ok : bool = pollUntil(deadline);
if (ok) { return 0; }
return 1;
} Numeric conversions
fn main() : i32 {
let a : i32 = 42;
let b : i64 = a; // i32 to i64: same signedness, widening
let c : f64 = a; // i32 to f64: exact, so implicit
let d : i32 = 3.9 as i32; // 3: truncates toward zero
let e : i32 = (0.0 - 3.9) as i32; // -3
println(b.toString() + c.toString() + d.toString() + e.toString());
return 0;
} The rules for implicit conversions:
| From | To | Rule |
|---|---|---|
i32 | i64 | implicit (same signedness, widening) |
i32 / u32 | f64 | implicit, because an f64 holds every value of either exactly |
i32 | f32 | needs as: the conversion would drop bits |
i64 | f64 | needs as: an f64 cannot hold every i64 |
u32 | i64 | needs as: implicit widening never crosses signedness |
f64 | i32 | never implicit (let n : i32 = 3.14; is refused) |
as converts between integer widths and between floats and integers. A
float-to-integer as truncates toward zero and saturates: 1e30 as i32 is 2147483647, and NaN as i32 is 0. It never wraps and never traps. The
named roundings are explicit methods:
fn main() : i32 {
let t : i32 = 3.9 as i32; // 3: toward zero
let r : i64 = (3.5).round(); // 4
let q : i64 = (2.5).round(); // 3: halves round away from zero
println(t.toString() + r.toString() + q.toString());
return 0;
} Overflow semantics
| Type | Behaviour |
|---|---|
i32, i64 arithmetic | wraps silently on overflow (two’s complement); a constant overflow is rejected at compile time |
u32, u64 arithmetic | wraps the same way: 0 - 5 on a u32 is 4294967291, and adding 1 to 4294967295 gives 0 |
| mixing a signed and an unsigned operand | rejected at compile time (E0037); write the cast that says which reading you meant |
| division by a literal zero | rejected at compile time |
| division by a runtime zero | aborts the process with a runtime error; guard the divisor yourself |
f64 arithmetic | follows IEEE-754 (Infinity, NaN) |
truncToInt(x) for x outside the i64 range | saturates to the nearest representable i64 |
fn add(a : i32, b : i32) : i32 {
return a + b;
}
fn main() : i32 {
let x : i32 = add(2_147_483_647, 1); // wraps to -2_147_483_648, no exception
println(x.toString());
return 0;
} If you need checked arithmetic, write the check yourself:
fn checkedAdd(a : i32, b : i32) : i32 ! ArithmeticException {
let r : i32 = a + b;
// Overflow iff a and b have the same sign and r has the other one.
if ((a > 0) == (b > 0) && (a > 0) != (r > 0)) {
throw ArithmeticException("integer overflow");
}
return r;
} Patterns
Clamping
fn clamp(x : f64, lo : f64, hi : f64) : f64 {
return x.max(lo).min(hi);
}
fn main() : i32 {
let input : f64 = 1.75;
let v : f64 = clamp(input, 0.0, 1.0);
println(v.toString());
return 0;
} Modulo with negative operands
// Axle's % is the remainder: it keeps the sign of the dividend.
// True modulo (always non-negative for a positive divisor):
fn modPos(a : i32, n : i32) : i32 {
let r : i32 = a % n;
if (r < 0) { return r + n; }
return r;
}
fn main() : i32 {
let rem : i32 = (-7) % 3; // -1, not 2
let m : i32 = modPos(-7, 3); // 2
println(rem.toString() + " " + m.toString());
return 0;
} Linear interpolation
fn lerp(a : f64, b : f64, t : f64) : f64 {
return a + (b - a) * t;
} Power-of-two rounding
fn nextPow2(n : i32) : i32 {
let mut p : i32 = 1;
while (p < n) { p = p * 2; }
return p;
} Limits / Uncabled
| Feature | State | Workaround |
|---|---|---|
| Time zones and local time | Not provided: LocalDateTime and the datetime functions are UTC | Convert offsets yourself by adding the offset in milliseconds before formatting |
Unsigned abs | Not provided: unsigned values have no magnitude to strip | The value is already non-negative; use min and max |
absChecked on f64 | Not provided: floats have no minimum that overflows | Use abs on the float; NaN propagates |
Per-instance Random state | Not provided: one process-wide stream | Use seed for reproducibility; a separate generator needs its own implementation |
| Cryptographic randomness | Not provided by Random | Use a platform CSPRNG through the C interop layer |
Integer exponentiation (pow on integers) | Not provided as a method: pow is on f64 and f32 | Use (x as f64).pow(e as f64) and convert back, or write a loop |
See also
std/numericreferencestd/numeric/randomreferencestd/time/datetimereferencestd/sysreference:now,sleep,nanoTime- Concept index: every numeric and time concept cross-linked