Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 1.0 KiB · at 2e2b18f

Write parseAmount(text), which parses a decimal money amount such as "1,234.56", "-12.5", "0.07" or "1000" and returns it as an integer number of cents.

The accepted grammar, matched against the whole string:

  • An optional leading -. No +, no whitespace anywhere, no exponent.
  • An integer part of ASCII digits, required. Either it has no commas at all, or it is comma-grouped: a first group of 1 to 3 digits followed by any number of , + exactly 3 digits.
  • No leading zeros: the integer part is either exactly 0 or starts with a digit from 1 to 9.
  • Optionally a . followed by exactly 1 or 2 digits.

The result must be exact: "1.15" is 115 cents and "0.07" is 7. A one-digit fraction means tenths ("-12.5" is -1250). Negative zero ("-0", "-0.00") returns 0, never -0.

Failures:

  • { kind: "invalid_amount", input } when text does not match the grammar; input is text unchanged.
  • { kind: "too_large" } when the text is well-formed but the absolute number of cents exceeds Number.MAX_SAFE_INTEGER.