Money Class
The Money class handles currency formatting, display, and mathematical operations.
Constructor
new Money(amount?: number | string, currency?: CurrencyCode)Create a new Money instance.
Parameters:
amount- The monetary amount (optional)currency- Currency code like 'USD', 'EUR', 'GBP' (optional)
Example:
const money = new Money(1234.56, 'USD');Static Methods
setDefaultCurrency()
Money.setDefaultCurrency(currency: CurrencyCode): voidSet the default currency for all Money instances.
of()
Money.of(amount: number | string, currency?: CurrencyCode): MoneyFactory method to create a Money instance.
format()
Money.format(amount: number | string, currency?: CurrencyCode): stringFormat an amount as currency (static method).
whole()
Money.whole(amount: number | string, currency?: CurrencyCode): stringFormat without decimal places (static method).
compact()
Money.compact(amount: number | string, currency?: CurrencyCode): stringFormat in compact notation (static method).
convert()
Money.convert(amount: number | string, from: CurrencyCode, to: CurrencyCode): Promise<Money>Convert amount between currencies (static method).
currencyCode()
Money.currencyCode(): CurrencyCodeGet the default currency code (static method).
currencySymbol()
Money.currencySymbol(): stringGet the default currency symbol (static method).
Instance Methods
Formatting Methods
format()
format(): stringFormat the amount with currency symbol and proper formatting.
whole()
whole(): stringFormat without decimal places.
compact()
compact(): stringFormat in compact notation (K, M, B, T).
Arithmetic Methods
add()
add(other: number | string | Money): MoneyAdd another amount.
subtract()
subtract(other: number | string | Money): MoneySubtract another amount.
multiply()
multiply(factor: number | string | Money): MoneyMultiply by a factor.
divide()
divide(divisor: number | string | Money): MoneyDivide by a divisor.
Rounding Methods
round()
round(digits?: number): MoneyRound to specified decimal places (default: 0).
ceil()
ceil(): MoneyRound up to nearest integer.
floor()
floor(): MoneyRound down to nearest integer.
Other Methods
absolute()
absolute(): MoneyGet absolute value.
mod()
mod(divisor: number | string | Money): MoneyCalculate modulus (remainder).
share()
share(total: number | string | Money, ratio: string | number): MoneyCalculate proportional share.
convert()
convert(to: CurrencyCode): Promise<Money>Convert to another currency.
setNegativeStyle()
setNegativeStyle(style: 'minus' | 'parentheses'): voidSet how negative amounts are displayed.
currencyCode()
currencyCode(): CurrencyCodeGet the currency code.
currencySymbol()
currencySymbol(): stringGet the currency symbol.
toString()
toString(): stringGet string representation (same as format()).
Types
CurrencyCode
type CurrencyCode = 'USD' | 'EUR' | 'GBP' | 'JPY' | /* ... many more */Union type of all supported currency codes.
Currency
type Currency = {
code: CurrencyCode;
symbol: string;
};Currency object with code and symbol.
