pify/decimal

Shopify sends money as decimal strings such as "49.90" or "49.9". A Decimal keeps the digits as an integer count of units at the scale the text carried, never a Float.

Types

units / 10^scale. "49.90" is 4990 units at scale 2.

pub opaque type Decimal
pub type DecimalError {
  DecimalInvalid(text: String)
}

Constructors

  • DecimalInvalid(text: String)
pub type ScaleError {
  ScaleDropsDigits(scale: Int)
}

Constructors

  • ScaleDropsDigits(scale: Int)

    The value has more significant fraction digits than scale holds.

Values

pub fn compare(left: Decimal, right: Decimal) -> order.Order

Compares values, not text: "49.9" equals "49.90".

pub fn from_hundredths(hundredths: Int) -> Decimal
pub fn from_scaled(units units: Int, scale scale: Int) -> Decimal

units / 10^scale. A negative scale multiplies: 5 at scale -1 is 50.

pub fn negate(decimal: Decimal) -> Decimal
pub fn parse(text: String) -> Result(Decimal, DecimalError)

Parse "49.9", "49.90", "0" or "-1.5". Rejects an empty string, a bare ., a leading +, exponents and grouping separators.

pub fn scale_error_to_string(error: ScaleError) -> String
pub fn to_scaled(
  decimal: Decimal,
  scale: Int,
) -> Result(Int, ScaleError)

The integer count of units at scale. "49.9" at scale 2 is 4990. Fails when the value has more significant fraction digits than scale, because dropping them would change the amount.

pub fn to_string(decimal: Decimal) -> String

The text form Shopify accepts on writes. It keeps the scale, so from_hundredths(4990) is "49.90".

✨ Search Document