money.format
v0.1.0 latestFormat an ISO 4217 Money object to its string representation using string-based division for exact output.
Format an ISO 4217 Money object to its string representation using string-based division for exact output.
Signature
function format(m: Money): string
Type Definitions:
Money— interface
Problem
Converting bigint minor units back to a human-readable string requires inserting the decimal point at the correct position based on scale. Using Number conversion for this step reintroduces precision issues for large amounts.
How It Works
Uses string-based division to avoid Number conversion. Always includes the full decimal places per the Money's scale. Output format is always 'amount currency' (e.g. '12.34 USD').
Boundaries
- Throws TypeError for invalid Money objects.
- Output format is always '12.34 USD' (amount + space + currency code).
- Negative amounts are prefixed with - (e.g. '-5.00 USD').
- scale=0 produces no decimal point (e.g. '1000 JPY').
Replaces
Common boilerplate this function replaces:
(Number(m.amount) / Math.pow(10, m.scale)).toFixed(m.scale) + ' ' + m.currency
Examples
money.format({ amount: 1234n, currency: "USD", scale: 2 }); // "12.34 USD"
money.format({ amount: 1000n, currency: "JPY", scale: 0 }); // "1000 JPY"
money.format({ amount: -500n, currency: "EUR", scale: 2 }); // "-5.00 EUR"
money.format({ amount: 5n, currency: "USD", scale: 2 }); // "0.05 USD"
Standards
Caveats
- Round-trip: parse(format(m)) should equal m for well-formed Money objects.
- No locale-aware formatting (no thousand separators, no locale-specific decimal mark). This is a stable representation, not display formatting.
FAQ
How to convert a Money object to a string?
money.format({ amount: 1234n, currency: 'USD', scale: 2 }) returns '12.34 USD'.
Does money.format add thousand separators?
No. money.format produces a stable representation without locale-specific formatting.
How are negative amounts formatted?
Prefixed with minus: money.format({ amount: -500n, currency: 'EUR', scale: 2 }) returns '-5.00 EUR'.
Is money.format a round-trip with money.parse?
Yes. money.parse(money.format(m)) should return the original Money object.
How are zero-scale currencies formatted?
No decimal point: money.format({ amount: 1000n, currency: 'JPY', scale: 0 }) returns '1000 JPY'.