Money Utilities
Utilities for handling monetary amounts with precision and proper formatting.
Overview
The money utilities provide essential functions for working with currency amounts, including formatting for display and currency conversion. These utilities use bigint for precise arithmetic to avoid floating-point errors common in financial calculations.
Key Concepts
Money Type
ts
type Money = {
readonly amount: bigint; // Amount in minor units (cents, pence, etc.)
readonly currency: string; // ISO 4217 currency code (USD, EUR, GBP, etc.)
};Why BigInt?
Financial calculations require exact precision. Using bigint to store amounts in minor units (cents) eliminates floating-point errors:
ts
// ❌ Bad - floating point errors
0.1 + 0.2; // 0.30000000000004
// ✅ Good - exact precision with bigint (cents)
10n + 20n; // 30n🔗 All Money Utilities
Usage Examples
Format Money
ts
import { currency } from '@vielzeug/toolkit';
const price = { amount: 123456n, currency: 'USD' };
currency(price); // '$1,234.56'Convert Currency
ts
import { exchange } from '@vielzeug/toolkit';
const usd = { amount: 100000n, currency: 'USD' };
const rate = { from: 'USD', to: 'EUR', rate: 0.85 };
exchange(usd, rate); // { amount: 85000n, currency: 'EUR' }Related Utilities
For arithmetic operations on monetary amounts, see:
- add - Add amounts
- subtract - Subtract amounts
- multiply - Multiply by scalars
- allocate - Split proportionally
- distribute - Split evenly