Functional Weave
Code in TypeScript

form.money-input@1.0.0

impl/python/format_money_input.py

2,532 bytes · the Python implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

from typing import List, NamedTuple

from .form_money_input_data import LOCALES  ← this capability’s own data, compiled from data/locales.json into the same file by fune build
from .money_amount import Money  ← from money.amount ^1.0.0 · built alongside by fune
from .money_currency_digits import currency_digits  ← from money.currency-digits ^1.0.0 · built alongside by fune


class NumberSeparators(NamedTuple):
    groups: List[str]  # every group separator money.parse accepts in this style
    group: str  # the one this capability writes
    decimal: str


def _lower(value: str) -> str:
    return "".join(chr(ord(c) + 32) if "A" <= c <= "Z" else c for c in value)


def number_style_for(locale: str) -> str:
    """The money.parse number style for a locale: the exact locale first
    (case-insensitive, "_" read as "-"), then its language alone."""
    wanted = _lower(locale.replace("_", "-"))
    for row in LOCALES:
        if _lower(row.locale) == wanted:
            return row.style
    language = wanted.split("-")[0]
    if language != "":
        for row in LOCALES:
            if _lower(row.locale) == language:
                return row.style
    raise ValueError(
        'unknown locale "%s": give a BCP 47 locale this capability lists, such as en-GB, de-DE or fr-FR' % locale
    )


def separators_of(style: str) -> NumberSeparators:
    """The separators of a money.parse number style, as money.parse reads them."""
    if style == "comma-dot":
        return NumberSeparators([","], ",", ".")
    if style == "dot-comma":
        return NumberSeparators(["."], ".", ",")
    if style == "space-comma":
        return NumberSeparators([" ", " ", " "], " ", ",")
    if style == "apostrophe-dot":
        return NumberSeparators(["'", "’"], "'", ".")
    raise ValueError('unknown number style "%s"' % style)


def write_amount(minor: int, digits: int, style: str) -> str:
    """Minor units written with thousands grouping and every decimal place, no symbol."""
    seps = separators_of(style)
    raw = str(abs(minor)).rjust(digits + 1, "0")
    whole = raw[: len(raw) - digits]
    fraction = raw[len(raw) - digits :]
    grouped = ""
    for i, ch in enumerate(whole):
        if i > 0 and (len(whole) - i) % 3 == 0:
            grouped += seps.group
        grouped += ch
    number = grouped + seps.decimal + fraction if digits > 0 else grouped
    return "-" + number if minor < 0 else number


def format_money_input(amount: Money, locale: str) -> str:
    """An amount as a money input shows it for editing: the locale's grouping
    and decimal mark, every decimal place, no symbol."""
    digits = currency_digits(amount.currency)
    return write_amount(amount.minor, digits, number_style_for(locale))