// Dec (ADR 0070): a 128-bit fixed-point decimal for money. import std/dec.{type Dec} import std/dict import std/io import std/process.{type proc} import std/result fn d :: s: String -> Dec { result.expect (dec.parse s) "a decimal" } pub fn main :: -> () / { // Exact decimal arithmetic: 0.1 + 0.2 == 0.3, unlike Float. The fixed // scale is canonical: 1.20 and 1.2 are one value. io.println "{d "0.1" + d "0.2" == d "0.3"} {d "1.20" == d "1.2"} {d "0.1" * d "0.1"}" // Division rounds half-even at the 18th place; rem is exact. io.println "{d "1" / d "3"} {d "2" / d "3"} {d "7" % d "2"} {d "7.5" % d "2"} {-d "1.5"}" // round ~places:, the money operation (half-even). io.println "{dec.round (d "2.5") ~places: 0} {dec.round (d "1.005") ~places: 2} {dec.round (d "1.015") ~places: 2} {dec.round (d "-2.5") ~places: 0}" // show trims trailing zeros; to_int truncates; abs. io.println "{d "1.20"} {d "42"} {dec.to_int (d "-12.99")} {dec.abs (d "-2.5")}" // Float conversions are explicit and go through the shortest decimal. io.println "{dec.from_float 0.1} {dec.to_float (d "0.1")} {dec.from_float (0.0 / 0.0)}" // The raw count of 10^-18 units, for binary codecs. io.println "{dec.scaled (d "1.5")} {dec.from_scaled 1500000000000000000}" // The range's edges: the minimum is a Dec; one quantum past the // maximum is not (the magnitude is unsigned, so -2^127/10^18 parses). io.println "{dec.parse "-170141183460469231731.687303715884105728"}" io.println "{dec.parse "170141183460469231731.687303715884105728"}" // A Dec is a key like any other (the hash is pinned, both backends). let prices = dict.from_list [(d "1.20", "one"), (d "2.5", "two")] io.println "{dict.get prices (d "1.2")} {dict.get prices (d "12")}" // And a value like any other: it can be sent. let inbox = process.subject () let _ = process.spawn fn { process.send inbox (d "3.14" * d "2") } io.println "{process.receive_forever inbox}" } //> True True 0.01 //> 0.333333333333333333 0.666666666666666667 1 1.5 -1.5 //> 2 1 1.02 -2 //> 1.2 42 -12 2.5 //> Ok(0.1) 0.1 Error(not a finite decimal in range: NaN) //> 1500000000000000000 Ok(1.5) //> Ok(-170141183460469231731.687303715884105728) //> Error(not a decimal: "170141183460469231731.687303715884105728") //> Some(one) None //> 6.28