std.dec - ZZ
Exact decimal arithmetic on strings. No floating-point drift: dec.add("0.1", "0.2") == "0.3". Scale capped at 18 places. Decimals are plain str in [-]digits[.digits] form.
import std.decPurpose
Section titled “Purpose”std.dec does exact base-10 arithmetic on decimal strings, avoiding the binary floating-point drift that makes 0.1 + 0.2 != 0.3 in float. All ops take and return str. Use for money, prices, taxes, and any domain where exact decimal semantics are required.
Quickstart
Section titled “Quickstart”import std.dec
dec.add("0.1", "0.2") // "0.3" (not "0.30000000000000004")dec.sub("1.0", "0.3") // "0.7"dec.mul("1.5", "2") // "3"dec.format("3.14159", 2) // "3.14"dec.cmp("1.5", "2") // -1dec.eq("0.30", "0.3") // true (normalized comparison)Edge cases & gotchas
Section titled “Edge cases & gotchas”- Scale capped at 18 places. Results beyond 18 fractional digits are truncated (not rounded) — verify against your domain’s precision needs.
- Input validation:
is_validchecks shape; arithmetic ops assume valid input — invalid strings are runtime errors. - No
dec.div— division can produce non-terminating decimals; scale viato_scaled/from_scaledor usefloatwhen approximate is acceptable. formatrounds/truncates toplaces— not banker’s rounding by default; test boundary cases (e.g.0.005).- Normalized comparison:
dec.eq("0.30", "0.3")→ true (trailing zeros don’t matter for equality).
Production patterns
Section titled “Production patterns”import std.dec
// Money: price * qty, format to 2 placesprice := dec.mul("19.99", "2") // "39.98"display := dec.format(price, 2) // "39.98"
// Exact comparisonsubtotal := dec.add("10.00", "5.00") // "15.00"tax := dec.mul(subtotal, "0.1") // "1.5"tax_total := dec.add(subtotal, tax) // "16.5"if dec.eq(tax_total, dec.add(subtotal, tax)) { println("ok")}API reference
Section titled “API reference”14 entries. Signatures come from the compiler’s own FuncSig table, so they match the runtime exactly; descriptions come from the module guide.
See also
Section titled “See also”std.json— Parse, stringify and read individual values out of JSON.std.map— Pure dictionary helpers over plain maps: lookup, merge and keys.std.set— Arrays with uniqueness: membership, union, intersection and difference.std.csv— An RFC 4180 subset: read rows, write rows, handle quotes and commas.std.property— Seeded generators and shrinking for property-based tests.
Full index: API reference · Standard library