money

Last updated on

Build and validate monetary amounts

Build and validate monetary amounts with currency. The Money primitive pairs a numeric amount with an ISO 4217 currency code.

Examples

Creating money values

// Object pattern
const price = p.money({ amount: 99.99, currency: 'USD' })

// Builder pattern
const price = p.money()
  .amount(99.99)
  .currency('USD')
  .build()

// Copy and modify
const discounted = p.money()
  .from(price)
  .amount(79.99)
  .build()

Parsing external data

// Parse unknown input (throws on error)
const price = p.money.parse(jsonData)

// Safe parsing (returns result object)
const result = p.money.safeParse(jsonData)
if (result.success) {
  console.log(`${result.data.currency} ${result.data.amount}`)
} else {
  console.error(result.error.message)
}

Using with forms

// As a field default
const form = p.form({
  name: 'product',
  fields: {
    price: {
      type: 'money',
      label: 'Price',
      default: { amount: 0, currency: 'USD' }
    }
  }
})

// When filling a form
const filled = form.fill({
  fields: {
    price: p.money({ amount: 29.99, currency: 'USD' })
  }
})

API

Object Pattern

p.money(input: Money): Money

Pass a Money object for validation. Returns the validated Money or throws on error.

const price = p.money({ amount: 150.00, currency: 'EUR' })

Builder Pattern

Chain methods to build a Money value incrementally:

All methods return MoneyBuilder and are chainable.

p.money()
amount: (value: number) => MoneyBuilder
Set the monetary amount
currency: (value: string) => MoneyBuilder
Set ISO 4217 currency code
from: (value: Money) => MoneyBuilder
Initialize from existing Money
build: () => Money
Build and validate

Static Methods

parse: (input: unknown) => Money
Parse unknown input (throws on error)
safeParse: (input: unknown) => Result<Money>
Parse unknown input (returns result object)

Properties

amount: number
Amount expressed in decimal form. Supports negative values for credits/refunds.
currency: string
ISO 4217 alpha-3 currency code (e.g., USD, EUR, GBP, JPY).

Validation

The Money primitive validates:

  • amount must be a valid finite number (not NaN or Infinity)
  • currency must be exactly three uppercase letters
// Valid
p.money({ amount: 100, currency: 'USD' })
p.money({ amount: -50, currency: 'USD' })  // Negative allowed
p.money({ amount: 0, currency: 'EUR' })    // Zero allowed
p.money({ amount: 99.999, currency: 'BTC' }) // Decimals allowed

// Invalid - throws Error
p.money({ amount: NaN, currency: 'USD' })

p.money({ amount: Infinity, currency: 'USD' })

p.money({ amount: 100 })

Common Currency Codes

CodeCurrency
USDUS Dollar
EUREuro
GBPBritish Pound
JPYJapanese Yen
CADCanadian Dollar
AUDAustralian Dollar
CHFSwiss Franc
CNYChinese Yuan
INRIndian Rupee
MXNMexican Peso

See ISO 4217 for the complete list.

On this page