Format a money value
Carry one amount from user input to localized currency output.
Table of contents
APIs used
- mount
- Starts a Valyrian.js application on a DOM target.
- Money
- Represents a monetary amount in integer cents and provides arithmetic operations.
- formatMoney
- Formats a Money or numeric value with the requested currency and locale options.
- parseMoneyInput
- Parses a localized text value into a Money amount.
Run this recipe
- Starting project
- Use the local TSX and ESM project from Stage 1 with Valyrian.js installed and its ESM browser build configured.
- File
- Replace src/client-entry.tsx with this recipe snippet.
- Run
- Run npm run build, serve public with npx --yes serve@14.2.5 public --listen 8000, open http://localhost:8000 and use the example's visible controls.
- Observable result
- The view renders the locale-aware representation of a 24.90 USD total.
Starting point
Start with a 19.90 subtotal and a five-dollar adjustment.
Steps
Parse 19.90 with two decimal places, add Money.fromCents(500) and format the result with en-US and USD.
tsimport { mount } from "valyrian.js";
import { Money, formatMoney, parseMoneyInput } from "valyrian.js/money";
const subtotal = parseMoneyInput("19.90", { decimalPlaces: 2 });
const total = subtotal.add(Money.fromCents(500));
mount("body", () => formatMoney(total, { currency: "USD", locale: "en-US" }));Result
The view renders the locale-aware representation of a 24.90 USD total.