Numbers and booleans#
Use Int for counts and indexes, Float for approximate measurements, and Decimal for base-ten calculations where rounding must be explicit. Booleans are true and false. Numeric types stay distinct: choose a type for the calculation and convert at its boundaries.
import Decimal from "@std/math/decimal.ms"
count := 3
ratio := 0.5
price := 12.50d
active := trueDecimal literals need import Decimal from "@std/math/decimal.ms".
Integer literals are Int, written in decimal, 0x hexadecimal or 0b binary. A fraction or exponent selects Float, and the d suffix selects Decimal (1d included). _ separates digits (1_000_000, 0xFF_FF, 0b1010_0101, 3.141_592). A hex or binary literal is a value, not a bit pattern, so 0xFFFF_FFFF_FFFF_FFFF is out of range. See the grammar
for literal forms.
| Type | Representation |
|---|---|
Int | Signed 64-bit integer with checked arithmetic; Int64 is the same type |
Int8, Int16, Int32 | Signed integers of that width with checked arithmetic |
UInt8, UInt16, UInt32, UInt64 | Unsigned integers of that width (0 to 255, 65535, 4294967295, 18446744073709551615) with checked arithmetic |
Float | IEEE 754 binary64; Float64 is another name for it |
Float32 | IEEE 754 binary32; every operation rounds to binary32 |
Decimal | Base-10, 34 significant digits, round half to even |
Bool | true or false |
Arithmetic and conversion#
- Arithmetic operands must have the same numeric type; the result has that type.
%takes integers of the same width. - Ordering comparisons need matching numeric types; equality follows the Equal rules . The expression table is authoritative.
- Int overflow and invalid Int/Decimal operations are programming faults; Float follows the rules below.
- Conversions between existing values use the methods below . A literal can take a sized type from context, as described below.
- Integer literals are checked against the signed 64-bit range.
9223372036854775808is accepted only when directly negated (parentheses do not help). - A Float literal rounds to binary64; one that rounds to infinity is rejected.
- A literal takes a sized type from an expected type or from the other operand of an operator:
x Int8 := 100andx / 2both type the literal asInt8. It must fit that type (x Int8 := 128is rejected), and a negated literal is checked after negation (-128fitsInt8). - Arithmetic made only of literals takes the type as a whole (
x Float32 := 0.1 + 0.2,y Int8 := 100 + 27), and each step must fit. A literal never changes kind:x Float32 := 1is rejected. - A
Float32literal is rounded once, directly from its decimal text to binary32 (not throughFloat). Sox Float32 := 340282356779733661637539395458142568447.0is the largest finiteFloat32, while the overflow midpoint...448.0is rejected. - The default types remain
Int/Int64andFloat/Float64; choose a sized type explicitly when storage or precision matters.
fn literals() Void {
smallest Int := -9223372036854775808
exponent Float := 1e3
mask Int := 0xFF_00
flags Int := 0b1010_0101
precise Decimal := 1e3d
// Rejected: an Int token does not become Float from context.
mismatch Float := 1
}Sized numbers#
Int8, Int16, Int32 and Float32 occupy 1, 2, 4 and 4 bytes in lists, user types, optionals, enums, maps and sets; locals and arguments keep full-width registers, so only storage shrinks. A List[Int8] of fifty million elements takes one eighth of the memory of a List[Int].
Arithmetic needs both operands to have the same type, so Int8 + Int32 is rejected. An Int8 operation that leaves -128 to 127 faults:
fn sized() Void {
a Int8 := 100
wide Int32 := 2000000000
ratio Float32 := 0.1
// Faults: 200 does not fit Int8.
b := a + a
// Rejected: operand types differ.
c := a + wide
}Float32 operations round once to binary32, so 0.1 + 0.2 is 0.3 for Float32 and 0.30000000000000004 for Float. Typed JSON supports sized integers and Float32, preserving their range checks. List indexes and literal match subjects still use Int; convert a sized integer at those boundaries. See numeric conversion
, list indexing
, matching literals
, and the JSON API
.
Numeric conversion#
| Receiver | Signature/result |
|---|---|
Int | to_float() Float; to_decimal() Decimal |
Any sized integer or Int | to_float32(), to_float(), to_decimal(); the integer conversions each type declares (see below) |
Float | to_float32() Float32? (null when a finite value exceeds the Float32 range; rounding is silent), truncate_to_int() Int? |
Float32 | to_float64(), to_float(), truncate_to_int() Int? |
Decimal, BigInt | to_float() Float? (null beyond the Float range); truncate_to_int() Int? |
String to Decimal | parse_decimal(text) Decimal! from @std/math/decimal.ms: sign, digits, optional fraction and exponent, exact or an EINVAL error (String.parse_int() and parse_float cover Int and Float) |
to_intN() returns the wider or equal type directly when every value fits (Int8.to_int32()) and an Optional of it otherwise (Int32.to_int8() is null for 70000).
Conversions to a float round to the nearest value, ties to even. Int to Decimal is exact, and Int to Float rounds once to the nearest binary64. A conversion to a float returns null only when a finite value is beyond the target range (1e300.to_float32(), or to_float() on a huge Decimal or BigInt); rounding itself is silent.
truncate_to_int drops the fraction toward zero; NaN, infinities, and out-of-range results yield null (1e300.truncate_to_int() is null; Float +2^63 fails, -2^63 converts).
Unsigned types follow the same rules with a lower bound of zero:
b UInt8 := 200is fine.x UInt8 := -1and256are rejected,a - bfaults whenb > a, and unary-is a compile error.to_uintN()exists where it is used:Inthas all of them,UInt64hasto_uint8andto_uint32, andUInt16hasto_uint8. Each returns anOptionalunless every source value fits (Int.to_uint8()isnullfor -1 or 256,UInt32.to_int32()isnullabove 2147483647).- Other pairs, such as
UInt8.to_int16(), are not declared. Go throughto_int():UInt8.to_int().to_int16().UInt8.to_int()widens directly;UInt64.to_int()isnullabove 9223372036854775807. UInt64literals and results above that bound print, compare, sort and divide as unsigned values.- A
Floatreaches an unsigned type through a chain such as(truncate_to_int() or 0).to_uint8(), because there is notruncate_to_uintN().
abs() and sign() are methods on every signed integer and float type, so no cast is needed. Unsigned values are never negative, so they have neither.
abs()returns the receiver’s own type.Int8-128has no absolute value and faults like any overflow.sign()on an integer returnsInt(-1, 0 or 1). On a float it returns the receiver’s type, with zeros and NaN unchanged.@std/math/math.mshas noabs,signorto_float32functions; the methods are the one spelling.
Every integer width, Float, Float32 and String also have a.min(b), a.max(b) and a.clamp(low, high). They need no import and return the receiver’s own type. Of equal values, the receiver is the result. Float orders NaN above every other value, and clamp with low greater than high is a programming fault. math.min, math.max, List.min and List.max accept any Comparable type, including Decimal, BigInt and the time types.
Runtime numeric outcomes#
Int#
+,-,*, and unary-fault when the result leaves theIntrange./truncates toward zero;%takes the dividend’s sign, soa = (a / b) * b + a % b.-7 / 2is -3 and-7 % 3is -1.- A zero divisor faults. Minimum Int
/ -1faults; Minimum Int% -1is zero.
These are programming faults. BigInt never overflows, and its divide and remainder return a Result (BigInt
).
Float#
Each operation rounds to binary64 (ties to even) with no fused multiply-add or reassociation. Overflow gives signed infinity; division by zero gives infinity (NaN for 0/0); invalid arithmetic gives NaN with no fault; underflow gives a subnormal or signed zero. Comparisons with NaN are false (!= is true, even against itself); positive and negative zero are equal. See string formatting
for non-finite spellings.
Decimal#
Values are c × 10^q: a signed coefficient c of at most 34 digits and exponent q from -6176 to 6111 (largest adjusted exponent 6144, smallest normal -6143, subnormals down to 1e-6176d). There is no NaN or infinity, and every zero formats as 0.
Each Decimal operator follows these steps:
- Compute the exact result. Division by zero faults.
- For a nonzero magnitude with adjusted decimal exponent
e, choose quantumq = max(e - 33, -6176). - Round the exact value divided by
10^qto an integer coefficient, ties to even. If it has 35 digits, shift one exact trailing zero intoq. - Require an equivalent representation with at most 34 coefficient digits and
qin range. Otherwise overflow faults.
Each operator rounds once: no intermediate rounding, reassociation, or saturation. Underflow gives a subnormal or zero. 1d / 3d is 0.3333333333333333333333333333333333d. Equality and ordering compare numeric values, ignoring scale.
A Decimal literal must be exactly representable: 1.00d is fine, but 35 significant digits (1.2345678901234567890123456789012345d) or an out-of-grid value is a compile error. 1e6144d and 1e-6176d are accepted; 1e6145d and 1e-6177d are not.
Every literal needs the d suffix to stay Decimal:
import Decimal from "@std/math/decimal.ms"
price := 100d
percent := 15d
discounted := price * (1d - percent / 100d)Validate expected bad input with expected failures ; see programming faults for invariants.
BigInt#
BigInt (from @std/math/math.ms) is an arbitrary-precision signed integer; it cannot overflow. It supports + - * / %, unary -, and < <= > >= == !=. Both operands must be BigInt: BigInt + Int is a type error, so convert with big_int_of_int(n). / truncates toward zero, % takes the sign of the dividend, and either by zero is a fault; divide and remainder return a Result instead. There are no bitwise operators; use bit_and, bit_or, bit_xor, bit_not, shift_left, and shift_right.
import big_int_of_int from "@std/math/math.ms"
big := big_int_of_int(2) * big_int_of_int(3) + big_int_of_int(1)Scale rounding and fixed places#
round(places:) yields a Decimal at a chosen scale; to_fixed(digits:) yields text with stable trailing zeros (25.50d shows as "25.50"). Both return Result[..., Error] with kind "ERANGE" or "EINVAL" and work on the exact value. Negative places round to tens, hundreds, and so on.
The default mode is RoundingMode.HalfEven; import RoundingMode from @std/math/decimal.ms for others:
| Mode | Rule | 2.5d at zero places | -2.5d at zero places |
|---|---|---|---|
HalfEven | Nearest; a tie chooses an even coefficient | 2d | -2d |
HalfAwayFromZero | Nearest; a tie rounds away from zero | 3d | -3d |
TowardZero | Discard the fractional coefficient | 2d | -2d |
Floor | Toward negative infinity | 2d | -3d |
Ceil | Toward positive infinity | 3d | -2d |
roundaccepts places -6144 to 6176, else"EINVAL";"ERANGE"if the result is not exactly representable. It never re-rounds to 34 digits.to_fixedaccepts digits 0 to 6176, else"EINVAL". It uses plain notation, keeps exactly the requested digits, and prints a rounded zero without a minus sign.
Decimal imposes no currency policy; scaled Int cents also work. This example rounds tax before adding it. Run it with ms test cents.ms:
import (
Decimal from "@std/math/decimal.ms",
expect_equal from "@std/test/test.ms",
)
fn amount_text() String! {
subtotal := 19.99d * 3d
tax := (subtotal * 0.0825d).round(places: 2)?
tax_text := tax.to_fixed(digits: 2)?
total_text := (subtotal + tax).to_fixed(digits: 2)?
padded := 25.50d.to_fixed(digits: 2)?
return ok(f"tax {tax_text} total {total_text} padded {padded}")
}
test "decimal amounts" {
amount_text()? | expect_equal("tax 4.95 total 64.92 padded 25.50")?
}Booleans#
Booleans drive if and while . Numbers are never implicitly Boolean.
Durations#
500.milliseconds(), 2.seconds(), and 2.minutes() are Duration values, built by methods of Int. A Duration is a signed 64-bit nanosecond count (2.seconds() is 2,000,000,000), and Duration arithmetic checks overflow. @std/time.ms also exports nanoseconds, microseconds, milliseconds, seconds, minutes, and hours as functions (sleep(seconds(2))); all take Int and fault when the nanosecond count overflows. Interpolating a Duration or calling to_string() gives human text such as 1m30.5s, 250ms, or 0s.
Use monotonic() from @std/time.ms to read an Instant for measuring elapsed time. An instant records a clock domain and a nanosecond tick; compare readings from the same domain, since crossing domains faults. Duration and Instant have no arithmetic operators: use add, subtract, shift and difference, which check overflow.