Skip to content

std::decimal

Operations on Decimal, the exact base-10 number of any size: conversions to and from Int, Float and String, division and rounding to a scale under a RoundingMode, sign, scale and absolute value, and arithmetic, Equatable, Comparable and Hashable impls that go by value, whatever the scale. + - * and Decimal.pow are exact. / rounds a quotient that does not end to 34 significant digits, half-even, and keeps one that ends exact, with no trailing zeros (10.00d / 4d is 2.5d). Decimal.divide rounds to a scale and mode you name, Decimal.divide_exact returns None for a quotient that does not end, and Decimal.sqrt and Decimal.round round as Decimal.divide does; Decimal.round_exact and Decimal.sqrt_exact return None instead of rounding. Decimal.split and Decimal.allocate divide an amount into parts that sum to it exactly.

Decimal.format and Decimal.format_percent write a decimal as a reader of a locale writes it, and Decimal.parse_in and Decimal.parse_percent_in read it back, by the rules std::int’s page gives for formatting and parsing numbers.

Import with import std::decimal.

type Decimal

An exact base-10 number of any size, the third numeric type beside Int and Float: + - * are always exact, / rounds to 34 significant digits, and nothing converts it to or from an Int or a Float implicitly. A literal carries a d suffix (1.50d). The scale shows when it prints (1.50d prints 1.50), and equality ignores it (1.50d == 1.5d).

fn to_int(d: Decimal) -> Int

type function on Decimal

Converts a Decimal to an Int by truncating toward zero. Exact at any size, since an Int holds a whole number of any size. Use Decimal.round first if a different rounding rule is needed.

assert Decimal.to_int(3.7d) == 3
assert Decimal.to_int(-3.7d) == -3
assert Decimal.to_int(123_456_789_012_345_678_901.9d) == 123_456_789_012_345_678_901
fn to_float(d: Decimal) -> Float

type function on Decimal

Converts a Decimal to a Float. A Float is binary, so most base-10 fractions are not exactly one, and a magnitude past Float’s range becomes ±Infinity. No Decimal becomes a Float implicitly.

assert Decimal.to_float(1.50d) == 1.5
fn divide(a: Decimal, b: NonZeroDecimal, scale: Int, mode: RoundingMode) -> Decimal

type function on Decimal

Divides a by b to exactly scale fractional digits, rounding the quotient with mode. It always returns a value at the named scale. Use it when the answer’s places are fixed, as cents are; a / b keeps 34 significant digits instead, and divide_exact never rounds. b is a NonZeroDecimal, so Decimal.divide(a, 0d, 2, mode) is a compile error and a computed b goes through NonZeroDecimal.try_from. A scale past Decimal’s, -2147483648 to 2147483647, traps.

assert Decimal.divide(10d, 3d, 2, RoundingMode.HalfEven) == 3.33d
assert Decimal.divide(10.00d, 4d, 2, RoundingMode.Down) == 2.50d
fn divide_exact(a: Decimal, b: NonZeroDecimal) -> Maybe<Decimal>

type function on Decimal

Divides a by b exactly: Some of the quotient when it terminates in base 10, None when it does not (10d by 3d). A quotient’s scale is a’s scale less b’s, or more when the quotient needs more digits (1d by 8d is 0.125d), and never below zero. b is a NonZeroDecimal, as Decimal.divide’s is, so it never traps.

assert Decimal.divide_exact(10.00d, 4d) == Some(2.50d)
assert Decimal.divide_exact(10.00d, 4d) |> Maybe.map(Decimal.to_string) == Some("2.50")
assert Decimal.divide_exact(1d, 8d) == Some(0.125d)
assert Decimal.divide_exact(10d, 3d) == None
fn round(d: Decimal, scale: Int, mode: RoundingMode) -> Decimal

type function on Decimal

Rounds d to exactly scale fractional digits using mode. Increasing the scale pads trailing zeros, which is always exact; decreasing it rounds. A negative scale rounds to tens, hundreds and so on. round_exact is the form that refuses to round. A scale past Decimal’s, -2147483648 to 2147483647, traps.

assert Decimal.round(3.14159d, 2, RoundingMode.HalfEven) == 3.14d
assert Decimal.round(2.5d, 0, RoundingMode.HalfEven) == 2d
assert Decimal.round(1d, 2, RoundingMode.Up) == 1.00d
fn round_exact(d: Decimal, scale: Int) -> Maybe<Decimal>

type function on Decimal

d at exactly scale fractional digits when that loses no digit: Some of it, and None when reaching scale would round. Increasing the scale pads trailing zeros, so it is always Some. Write ! after it where the digits are known to fit.

assert Decimal.round_exact(1.50d, 1) == Some(1.5d)
assert Decimal.round_exact(1.5d, 3) |> Maybe.map(Decimal.to_string) == Some("1.500")
assert Decimal.round_exact(1.55d, 1) == None
fn pow(d: Decimal, exp: NonNegativeInt) -> Decimal

type function on Decimal

d multiplied by itself exp times, exactly, as * multiplies: the scale is exp times d’s, so 1.5d squared is 2.25d and 1.50d squared 2.2500d. Decimal.pow(d, 0) is 1d for every d, 0d included. exp is a NonNegativeInt: a negative power is a quotient that may not end, so write 1d / Decimal.pow(d, n), or Decimal.divide to name the rounding. A result whose scale is past Decimal’s (about two billion digits) traps.

assert Decimal.pow(1.5d, 2) == 2.25d
assert Decimal.to_string(Decimal.pow(1.50d, 2)) == "2.2500"
assert Decimal.pow(2d, 64) == 18446744073709551616d
assert Decimal.pow(0d, 0) == 1d
assert 1d / Decimal.pow(2d, 3) == 0.125d
fn sqrt(d: NonNegativeDecimal, scale: Int, mode: RoundingMode) -> NonNegativeDecimal

type function on Decimal

The square root of d to exactly scale digits after the decimal point, rounding with mode, as Decimal.divide rounds its quotient. A root that ends within scale digits is exact under every mode, and sqrt_exact is the form that refuses to round; a scale past Decimal’s, -2147483648 to 2147483647, traps. d is a NonNegativeDecimal, and so is its root; a value from data goes through NonNegativeDecimal.try_from.

assert Decimal.sqrt(2d, 4, RoundingMode.HalfEven) == 1.4142d
assert Decimal.sqrt(2d, 4, RoundingMode.Up) == 1.4143d
assert Decimal.to_string(Decimal.sqrt(6.25d, 3, RoundingMode.Down)) == "2.500"
assert Decimal.sqrt(0d, 2, RoundingMode.HalfEven) == 0d
fn sqrt_exact(d: NonNegativeDecimal, scale: Int) -> Maybe<NonNegativeDecimal>

type function on Decimal

The square root of d to exactly scale digits after the decimal point when it ends within them: Some of it, and None when the root would need rounding at scale.

assert Decimal.sqrt_exact(6.25d, 3) |> Maybe.map(Decimal.to_string) == Some("2.500")
assert Decimal.sqrt_exact(2d, 4) == None
fn normalize(d: Decimal) -> Decimal

type function on Decimal

Strips trailing fractional zeros, returning the value at its smallest scale. Whole-number digits stay (100d stays 100d, scale 0), and zero goes to scale 0. Equality and hashing already ignore the scale; normalize is for showing a value without its trailing zeros.

assert Decimal.normalize(1.50d) == 1.5d
assert Decimal.normalize(100.00d) == 100d
fn scale(d: Decimal) -> Int

type function on Decimal

Returns the scale of d, its number of fractional digits. 1.50d has scale 2 and 1.5d scale 1, though the two are equal under ==.

assert Decimal.scale(1.50d) == 2
assert Decimal.scale(5d) == 0
fn abs(d: Decimal) -> NonNegativeDecimal

type function on Decimal

Returns |d| (scale preserved), a NonNegativeDecimal.

assert Decimal.abs(-1.50d) == 1.50d
fn negate(d: Decimal) -> Decimal

type function on Decimal

Returns -d (scale preserved). Negating zero stays zero.

assert Decimal.negate(1.50d) == -1.50d
fn sign(d: Decimal) -> Int

type function on Decimal

Returns the sign of d as -1, 0, or +1 (by mathematical value).

assert Decimal.sign(-1.50d) == -1
assert Decimal.sign(0.00d) == 0
assert Decimal.sign(1.50d) == 1
fn is_zero(d: Decimal) -> Bool

type function on Decimal

True if d is exactly zero (at any scale: 0d, 0.00d are both zero).

assert Decimal.is_zero(0.00d)
refute Decimal.is_zero(1.50d)
fn split(d: Decimal, n: PositiveInt, scale: NonNegativeInt) -> List<Decimal>

type function on Decimal

d split into n parts that sum to it exactly and differ by at most one unit of the scaleth digit after the point: a bill shared by n people. The leftover units go one each to the first parts, so the larger parts come first. It is Decimal.allocate with n equal ratios.

scale is the least number of digits after the point a part has: when d has more, it is split in units of its own last digit, so 0.125d split two ways at scale 2 is 0.063d and 0.062d, which still sum to it. n is a PositiveInt, so there is at least one part, and scale a NonNegativeInt.

assert Decimal.split(100d, 3, 2) == [33.34d, 33.33d, 33.33d]
assert Display.to_string(Decimal.split(100d, 3, 2)) == "[33.34, 33.33, 33.33]"
assert Decimal.split(-0.05d, 2, 2) == [-0.03d, -0.02d]
assert Decimal.split(10d, 4, 0) == [3d, 3d, 2d, 2d]
assert Decimal.split(0.125d, 2, 2) == [0.063d, 0.062d]
fn allocate(d: Decimal, ratios: Ratios, scale: NonNegativeInt) -> List<Decimal>

type function on Decimal

d split into parts proportional to ratios, one part per ratio, that sum to it exactly: a payment shared 70 to 30, or a discount spread over a cart’s lines by their prices. Each part is its share rounded toward zero to a unit of the scaleth digit after the point; the units left over go one each to the parts in the order of ratios, skipping a zero ratio, so a zero ratio’s part is always zero. This is Fowler’s allocate. A negative d is split as its magnitude is, and each part takes its sign.

scale is the least number of digits after the point a part has: when d has more, it is split in units of its own last digit, so the parts still sum to it, and each part has that many digits. ratios are Ratios, so an empty list, a negative ratio, or ratios that are all zero are compile errors in a literal, and ratios computed when the program runs go through Ratios.try_from. scale is a NonNegativeInt.

import std::decimal.Ratios

assert Decimal.allocate(0.05d, [3, 7], 2) == [0.02d, 0.03d]
assert Decimal.allocate(10d, [70, 0, 30], 2) == [7d, 0d, 3d]
assert Decimal.allocate(-1d, [1, 2], 2) == [-0.34d, -0.66d]
assert Decimal.allocate(1.5d, [1, 1], 0) == [0.8d, 0.7d]

prices = [3, 1]
shares = Ratios.try_from(prices)!
assert Decimal.allocate(1d, shares, 2) == [0.75d, 0.25d]
fn format(d: Decimal, locale: Locale, fraction: ClosedRange<NonNegativeInt> = Range.from(0), grouping: Bool = True, mode: RoundingMode = RoundingMode.HalfEven) -> String

type function on Decimal

d as a reader of locale writes it, with as many digits after the decimal point as its scale has, held within fraction: padded with zeros to its start and rounded to its end. fraction is one ClosedRange<NonNegativeInt>, 2..=2, so a negative count or a backwards range is a compile error. Range.from(2), which has no end, is at least two digits and every digit of the scale past them. By default it is Range.from(0), so every digit of the scale is kept and none rounded: 1234.50d is 1,234.50 in en. A digit past the end is rounded as mode says, half to even unless it says otherwise, as Money.round rounds.

assert Decimal.format(1234.50d, Locale"de") == "1.234,50"
assert Decimal.format(1234.50d, Locale"en") == "1,234.50"
assert Decimal.format(1234567.89d, Locale"en") == "1,234,567.89"
assert Decimal.format(-0.5d, Locale"sv") == "−0,5"
assert Decimal.format(1234.5d, Locale"en", grouping: False) == "1234.5"
assert Decimal.format(0.125d, Locale"en", fraction: 0..=2) == "0.12"
assert Decimal.format(0.125d, Locale"en", fraction: 0..=2, mode: RoundingMode.HalfUp) == "0.13"
assert Decimal.format(12d, Locale"fr", fraction: 2..=2) == "12,00"
assert Decimal.format(1.5d, Locale"en", fraction: Range.from(2)) == "1.50"
assert Decimal.format(1.23456d, Locale"en", fraction: Range.from(2)) == "1.23456"
fn format_percent(d: Decimal, locale: Locale, fraction: ClosedRange<NonNegativeInt> = Range.from(0), mode: RoundingMode = RoundingMode.HalfEven) -> String

type function on Decimal

d as a percentage in locale: d times 100, exactly, with the locale’s percent sign where the locale’s pattern puts it (%26 in tr), and the digits after the decimal point the percentage’s scale has (two fewer than d’s), held within fraction and rounded by mode as Decimal.format does. By default every digit is kept.

assert Decimal.format_percent(0.125d, Locale"en") == "12.5%"
assert Decimal.format_percent(0.5d, Locale"de") == "50\u{a0}%"
assert Decimal.format_percent(0.26d, Locale"tr") == "%26"
assert Decimal.format_percent(0.12345d, Locale"en", fraction: 0..=1) == "12.3%"
assert Decimal.format_percent(0.12355d, Locale"en", fraction: 0..=2) == "12.36%"
assert Decimal.format_percent(0.5d, Locale"en", fraction: 1..=1) == "50.0%"
fn parse_in(text: String, locale: Locale, lenient: Bool = False) -> Result<Decimal, NumberParseError>

type function on Decimal

Read text a reader of locale wrote as a Decimal, strictly unless lenient: True, as Int.parse_in reads an Int. The digits typed after the decimal separator are the scale: 12,50 is 12.50d.

assert Decimal.parse_in("1.234,5", Locale"de") == Ok(1234.5d)
assert Decimal.parse_in("12,50", Locale"pl") |> Result.map(&Display.to_string(&1)) == Ok("12.50")

assert Decimal.parse_in("1.234,5", Locale"en") == Err(NumberParseError.Unexpected{at: 5, text: ","})

assert Decimal.parse_in("∞", Locale"en") == Err(NumberParseError.OutOfRange)
fn parse_percent_in(text: String, locale: Locale, lenient: Bool = False) -> Result<Decimal, NumberParseError>

type function on Decimal

Read a percentage a reader of locale wrote, as a fraction, divided by 100 exactly: 12,5 % is 0.125d. The percent sign is required, where the locale puts it unless lenient: True, which takes it on either side and ASCII % for the locale’s sign.

assert Decimal.parse_percent_in("12,5\u{a0}%", Locale"de") == Ok(0.125d)
assert Decimal.parse_percent_in("12.5%", Locale"en") == Ok(0.125d)
assert Decimal.parse_percent_in("%12.5", Locale"en", True) == Ok(0.125d)

assert Decimal.parse_percent_in("12.5", Locale"en")
    == Err(NumberParseError.Unexpected{at: 4, text: ""})

impl Display for Decimal

fn to_string(d: Decimal) -> String

impl Display.to_string

Returns d in digits at its scale, the text io.print and string interpolation write. Trailing zeros are kept (1.50d is "1.50").

assert Decimal.to_string(1.50d) == "1.50"
assert Decimal.to_string(100d) == "100"

impl Add<Decimal, Decimal> for Decimal

fn add(lhs: Decimal, rhs: Decimal) -> Decimal

impl Add.add

impl Summable for Decimal

fn empty_sum() -> Decimal

impl Summable.empty_sum

The sum of no Decimals: 0d, at scale 0. A sum takes the larger scale of its operands, so x + 0d keeps x’s scale.

assert Decimal.empty_sum() == 0d
assert Decimal.to_string(1.50d + Decimal.empty_sum()) == "1.50"

impl Subtract<Decimal, Decimal> for Decimal

fn subtract(lhs: Decimal, rhs: Decimal) -> Decimal

impl Subtract.subtract

impl Multiply<Decimal, Decimal> for Decimal

fn multiply(lhs: Decimal, rhs: Decimal) -> Decimal

impl Multiply.multiply

Decimal.divide Divide<NonZeroDecimal, Decimal>

Section titled “Decimal.divide Divide<NonZeroDecimal, Decimal>”

impl Divide<NonZeroDecimal, Decimal> for Decimal

fn divide(lhs: Decimal, rhs: NonZeroDecimal) -> Decimal

impl Divide.divide

lhs / rhs: the quotient rounded half-even to 34 significant digits, with no trailing zeros after the point. A quotient that ends within 34 digits is exact. The divisor is a NonZeroDecimal, as Int’s / takes a NonZeroInt.

assert Decimal.to_string(10.00d / 4d) == "2.5"
assert Decimal.to_string(10d / 3d) == "3.333333333333333333333333333333333"
assert Decimal.to_string(1d / 4d) == "0.25"
assert Decimal.scale(6.00d / 3d) == 0
assert Decimal.to_string(-2d / 3d) == "-0.6666666666666666666666666666666667"

impl Remainder<NonZeroDecimal, Decimal> for Decimal

fn remainder(lhs: Decimal, rhs: NonZeroDecimal) -> Decimal

impl Remainder.remainder

lhs % rhs: lhs - rhs * q, where q is the quotient truncated toward zero. Exact, never rounds, and takes the sign of lhs; the scale is the larger of the operands’. The divisor is a NonZeroDecimal.

assert 10.5d % 3d == 1.5d
assert Decimal.to_string(7.25d % 0.5d) == "0.25"
assert -7.5d % 2d == -1.5d
assert Decimal.to_string(10d % 2.50d) == "0.00"

impl Productable for Decimal

fn empty_product() -> Decimal

impl Productable.empty_product

The product of no Decimals: 1d, at scale 0. A product’s scale is the sum of its operands’, so x * 1d keeps x’s scale.

assert Decimal.empty_product() == 1d
assert Decimal.to_string(1.50d * Decimal.empty_product()) == "1.50"

impl Debug for Decimal

fn inspect(d: Decimal) -> String

impl Debug.inspect

impl Equatable for Decimal

fn equal(a: Decimal, b: Decimal) -> Bool

impl Equatable.equal

impl Hashable for Decimal

fn hash(d: Decimal) -> Int

impl Hashable.hash

impl Comparable for Decimal

fn compare(a: Decimal, b: Decimal) -> Ordering

impl Comparable.compare

impl Steppable for Decimal

fn step_by(value: Decimal, by: Decimal) -> Maybe<Decimal>

impl Steppable.step_by

Returns value + by, exactly, as Decimal’s + adds.

assert Decimal.step_by(1.0d, 0.1d) == Some(1.1d)
subtype NonZeroDecimal Decimal when fn d -> d != 0d

A Decimal that is not zero, so dividing by one cannot trap. A literal is checked when the program is compiled; NonZeroDecimal.try_from(d) checks a value at run time. It is in the prelude.

subtype: NonZeroDecimal is a subtype of Decimal. A literal where a NonZeroDecimal is expected is checked when the program is compiled; NonZeroDecimal.try_from(...) checks a value when it runs.

d: NonZeroDecimal = 4d
assert 10d / d == 2.5d
assert NonZeroDecimal.try_from(0.00d) == None
fn try_from(value: Decimal) -> Maybe<NonZeroDecimal>

type function on NonZeroDecimal

Some of the value when it satisfies NonZeroDecimal’s rules, None when it does not.

subtype NonNegativeDecimal Decimal when fn d -> d >= 0d

A Decimal that is zero or more: an amount, a rate, what Decimal.sqrt takes. A literal is checked when the program is compiled; NonNegativeDecimal.try_from(d) checks a value at run time. It is in the prelude.

subtype: NonNegativeDecimal is a subtype of Decimal. A literal where a NonNegativeDecimal is expected is checked when the program is compiled; NonNegativeDecimal.try_from(...) checks a value when it runs.

r: NonNegativeDecimal = 6.25d
assert Decimal.sqrt(r, 1, RoundingMode.HalfEven) == 2.5d
assert NonNegativeDecimal.try_from(-0.01d) == None
fn try_from(value: Decimal) -> Maybe<NonNegativeDecimal>

type function on NonNegativeDecimal

Some of the value when it satisfies NonNegativeDecimal’s rules, None when it does not.

subtype PositiveDecimal NonNegativeDecimal and NonZeroDecimal when fn d -> d > 0d

A Decimal greater than zero. It refines both NonNegativeDecimal and NonZeroDecimal, so a PositiveDecimal passes wherever either, or a Decimal, is expected. It is in the prelude.

subtype: PositiveDecimal is a subtype of NonNegativeDecimal and NonZeroDecimal, and through them Decimal. A literal where a PositiveDecimal is expected is checked when the program is compiled; PositiveDecimal.try_from(...) checks a value when it runs.

assert PositiveDecimal.try_from(0.5d) == Some(0.5d)
assert PositiveDecimal.try_from(0d) == None
fn try_from(value: Decimal) -> Maybe<PositiveDecimal>

type function on PositiveDecimal

Some of the value when it satisfies PositiveDecimal’s rules, None when it does not.

subtype Ratios List<Int> when fn ratios -> Iter.all_match(ratios, fn r -> r >= 0) and Iter.any_match(ratios, fn r -> r > 0)

The ratios Decimal.allocate and Money.allocate split an amount by: at least one, none negative, and not all zero, so every part has a share to take. A literal, [70, 30], is checked when the program is compiled; Ratios.try_from(xs) checks ratios computed when it runs. It is not in the prelude: import std::decimal.Ratios to name it.

subtype: Ratios is a subtype of List<Int>. A literal where a Ratios is expected is checked when the program is compiled; Ratios.try_from(...) checks a value when it runs.

import std::decimal.Ratios

r: Ratios = [70, 0, 30]
assert Decimal.allocate(10d, r, 2) == [7d, 0d, 3d]
assert Ratios.try_from([]) == None
assert Ratios.try_from([1, -1]) == None
assert Ratios.try_from([0, 0]) == None
assert Ratios.try_from([0, 2]) == Some([0, 2])
fn try_from(value: List<Int>) -> Maybe<Ratios>

type function on Ratios

Some of the value when it satisfies Ratios’s rules, None when it does not.

enum RoundingMode
    Up
    Down
    Ceiling
    Floor
    HalfUp
    HalfDown
    HalfEven
end

How a Decimal operation rounds. Decimal.divide, Decimal.round and Decimal.sqrt take one with no default. Decimal.format and Float.round default to HalfEven, which Decimal’s / always uses.

  • Up: away from zero
  • Down: toward zero (truncate)
  • Ceiling: toward +∞
  • Floor: toward −∞
  • HalfUp: nearest; ties away from zero
  • HalfDown: nearest; ties toward zero
  • HalfEven: nearest; ties to even (banker’s rounding)

No mode asserts that nothing rounds: Decimal.round_exact, Decimal.divide_exact and Decimal.sqrt_exact return None when a digit would be lost.

impl Debug for RoundingMode

fn inspect(value: RoundingMode) -> String

impl Debug.inspect

impl Display for RoundingMode

fn to_string(value: RoundingMode) -> String

impl Display.to_string