Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { CURRENCIES } from "./money_format_data.ts"; ← this capability’s own data, compiled from data/currencies.json into the same file by fune build
import { type Money } from "./money_amount.ts"; ← from money.amount ^1.0.0 · built alongside by fune
/**
* Render a monetary amount as text.
*
* Not every currency has two decimal places: yen has none, Kuwaiti dinar has
* three. Dividing by 100 to display an amount is wrong about as often as it
* is right, so the precision comes from the currency table.
*/
export function formatMoney(amount: Money): string {
const format = CURRENCIES.find((c) => c.code === amount.currency);
if (format === undefined) {
throw new RangeError(`no formatting rules for currency "${amount.currency}"`);
}
const negative = amount.minor < 0;
const digits = Math.abs(amount.minor).toString().padStart(format.digits + 1, "0");
const whole = digits.slice(0, digits.length - format.digits);
const fraction = digits.slice(digits.length - format.digits);
let grouped = "";
for (let i = 0; i < whole.length; i++) {
if (i > 0 && (whole.length - i) % 3 === 0) grouped += format.groupSeparator;
grouped += whole[i];
}
const number = format.digits > 0 ? grouped + format.decimalSeparator + fraction : grouped;
const body = format.symbolBefore ? format.symbol + number : number + format.symbol;
return negative ? "-" + body : body;
}