Functional Weave
Code in Rust

form.money-input@1.0.0

impl/python/money_input_format.py

2,097 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 NamedTuple

from .form_money_input_format_money_input import number_style_for, separators_of, write_amount  ← formatMoneyInput, another function of this group · built into the same file, even by a slim install
from .form_money_input_types import MoneyInputFormat
from .money_currency_digits import currency_digits  ← from money.currency-digits ^1.0.0 · built alongside by fune
from .money_format_data import CURRENCIES  ← money.format’s rule data (^1.0.0) · built alongside by fune
from .money_parse_data import CURRENCY_SYMBOLS  ← money.parse’s rule data (^1.0.0) · built alongside by fune


class CurrencySymbol(NamedTuple):
    symbol: str
    raw: str  # money.format's own spacing ("CHF ", " kr"), for a sentence
    before: bool


def currency_symbol(currency: str) -> CurrencySymbol:
    """money.format's symbol where it has the currency, else the first symbol
    money.parse knows (before the amount), else the ISO code itself."""
    for row in CURRENCIES:
        if row.code == currency:
            return CurrencySymbol(row.symbol.strip(" "), row.symbol, row.symbol_before)
    for row in CURRENCY_SYMBOLS:
        if row.code == currency:
            return CurrencySymbol(row.symbol, row.symbol, True)
    return CurrencySymbol(currency, currency + " ", True)


def money_for_message(minor: int, currency: str, locale: str) -> str:
    """An amount in a sentence: "£10.00", "100,00 kr", "€1.000,00"."""
    digits = currency_digits(currency)
    sym = currency_symbol(currency)
    number = write_amount(abs(minor), digits, number_style_for(locale))
    body = sym.raw + number if sym.before else number + sym.raw
    return "-" + body if minor < 0 else body


def money_input_format(currency: str, locale: str) -> MoneyInputFormat:
    """What a money input for this currency and locale shows: the symbol,
    the separators, and 1234.50 written the locale's way."""
    digits = currency_digits(currency)
    style = number_style_for(locale)
    seps = separators_of(style)
    sym = currency_symbol(currency)
    example = int("1234" + "50".ljust(digits, "0")[:digits])
    return MoneyInputFormat(
        currency=currency,
        symbol=sym.symbol,
        symbol_before=sym.before,
        digits=digits,
        group_separator=seps.group,
        decimal_separator=seps.decimal,
        example=write_amount(example, digits, style),
    )