dinero.js Documentation

repository·main·Indexed 27 days ago

https://github.com/dinerojs/dinero.js

A JavaScript and TypeScript library for the safe creation, calculation, and formatting of monetary values. It provides immutable, type-safe primitives to handle money manipulation, including conversions, non-decimal currencies, and scale normalization. Features include a comprehensive API for comparisons (compare, equal, greaterThan, lessThan), formatting tools like toDecimal, and specialized skills for AI coding agents.

Tokens
39K
Snippets
129
Records
197
Agent score
91%

What's inside dinero.js

  1. Replicate v1.x locale formatting in v2

    main

    v2 has dropped built-in support for locales to remain dependency-free. To replicate the formatting behavior from v1.x, you must create a custom formatter that wraps the native Intl API using toDecimal.

    import { toDecimal } from 'dinero.js';
    
    function createIntlFormatter(locale, options = {}) {
      function transformer({ value, currency }) {
        return Number(value).toLocaleString(locale, {
          ...options,
          style: 'currency',
          currency: currency.code,
        });
      }
    
      return function formatter(dineroObject) {
        return toDecimal(dineroObject, transformer);
      };
    }
    
    export const intlFormat = createIntlFormatter('en-US');
    
    // Usage:
    // intlFormat(dineroObject) -> "$5.00"
    import { toDecimal } from 'dinero.js';
    
    function createIntlFormatter(locale, options = {}) {
      function transformer({ value, currency }) {
        return Number(value).toLocaleString(locale, {
          ...options,
          style: 'currency',
          currency: currency.code,
        });
      }
    
      return function formatter(dineroObject) {
        return toDecimal(dineroObject, transformer);
      };
    }
    
    export const intlFormat = createIntlFormatter('en-US');
  2. Use built-in ISO 4217 currencies

    main

    Dinero.js provides standard ISO 4217 currency objects via specific subpath exports.

    For standard numeric amounts, import from dinero.js/currencies. For bigint amounts, import from dinero.js/bigint/currencies.

    Warning: Currency data may change between Dinero.js versions. If you require absolute stability, define your own custom currency objects or pin your Dinero.js version.

    import { dinero } from 'dinero.js';
    import { USD, EUR } from 'dinero.js/currencies';
    
    const d1 = dinero({ amount: 1000, currency: USD });
    const d2 = dinero({ amount: 1000, currency: EUR });
  3. Use the `dinero-currency-patterns` skill

    main

    Install this skill to teach your AI agent currency handling patterns. It covers: defining type-safe custom currencies, compile-time currency mismatch detection, validating currency codes from external sources, converting with scaled exchange rates, database storage schemas, and payment service integration (Stripe, PayPal, Square).

    npx skills add dinerojs/skills --skill dinero-currency-patterns
  4. Sort arrays of Dinero objects

    main

    The compare function is designed to be used directly as a comparator for Array.prototype.sort() to sort lists of Dinero objects.

    • Ascending (Low to High): Pass compare directly to .sort().
    • Descending (High to Low): Use an arrow function to reverse the arguments: (a, b) => compare(b, a).
    import { dinero, compare } from 'dinero.js';
    import { USD } from 'dinero.js/currencies';
    
    const d1 = dinero({ amount: 900, currency: USD });
    const d2 = dinero({ amount: 500, currency: USD });
    const d3 = dinero({ amount: 800, currency: USD });
    
    const lowToHigh = [d1, d2, d3].sort(compare);
    const highToLow = [d1, d2, d3].sort((a, b) => compare(b, a));
  5. Use Dinero.js with bigint

    main

    For representing colossal amounts of money or high-exponent cryptocurrencies that exceed the safe limits of the JavaScript number type, use the bigint variant of Dinero.js.

    Important: You must import dinero and currencies from the dinero.js/bigint subpaths. Do not mix currencies from dinero.js/currencies with the bigint variant, as they use number for base and exponent.

    import { dinero, add } from 'dinero.js/bigint';
    import { USD } from 'dinero.js/bigint/currencies';
    
    const d1 = dinero({ amount: 500n, currency: USD });
    const d2 = dinero({ amount: 100n, currency: USD });
    
    add(d1, d2); // a Dinero object with amount `600n`
  6. Leverage currency type safety with TypeScript

    main

    When using TypeScript, Dinero.js uses the TCurrency type parameter to represent currency codes as string literal types. This allows the compiler to catch currency mismatches in operations like add, subtract, equal, compare, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, minimum, maximum, haveSameAmount, and normalizeScale before runtime.

    Built-in ISO 4217 currencies (like USD or EUR) are pre-typed to enable this behavior automatically.

    import { dinero, add } from 'dinero.js';
    import { USD, EUR } from 'dinero.js/currencies';
    
    const d1 = dinero({ amount: 500, currency: USD }); // Dinero<number, 'USD'>
    const d2 = dinero({ amount: 100, currency: USD }); // Dinero<number, 'USD'>
    const d3 = dinero({ amount: 100, currency: EUR }); // Dinero<number, 'EUR'>
    
    add(d1, d2); // OK
    add(d1, d3); // Type error: 'EUR' is not assignable to 'USD'
  7. Use scaled amounts instead of floats in v2

    main

    To prevent precision loss, v2 replaces float arguments in methods like convert, multiply, and allocate with scaled amounts. A scaled amount is an object containing an amount (integer) and a scale (the position of the decimal point).

    Example scaled amount for 0.89: { amount: 89, scale: 2 }.

    Convert

    import { dinero, convert } from 'dinero.js';
    import { USD, EUR } from 'dinero.js/currencies';
    
    const rates = { EUR: { amount: 89, scale: 2 } }; // Represents 0.89
    const d = dinero({ amount: 500, currency: USD });
    
    convert(d, EUR, { rates });

    Multiply

    import { dinero, multiply } from 'dinero.js';
    import { USD } from 'dinero.js/currencies';
    
    const multiplier = { amount: 2001, scale: 3 }; // Represents 2.001
    const d = dinero({ amount: 401, currency: USD });
    
    multiply(d, multiplier);

    Allocate

    import { dinero, allocate } from 'dinero.js';
    import { USD } from 'dinero.js/currencies';
    
    const ratios = [
      { amount: 505, scale: 1 }, // 50.5
      { amount: 495, scale: 1 }, // 49.5
    ];
    const d = dinero({ amount: 100, currency: USD });
    
    allocate(d, ratios);
  8. Create Dinero objects from float values

    main

    Dinero.js objects must be instantiated using integers representing the minor currency units (e.g., cents for USD). To avoid precision issues, do not pass floats directly to the dinero() constructor.

    If you have float amounts (like 19.99), you should implement a helper function to convert the float into the appropriate integer amount based on the currency's scale/exponent before calling dinero().

    import { dinero, add, subtract } from 'dinero.js';
    import { USD } from 'dinero.js/currencies';
    
    // Standard way: use integers (minor units)
    const d = dinero({ amount: 1999, currency: USD });
    
    // Helper for floats
    function dineroFromFloat({ amount: float, currency, scale }) {
      const factor = currency.base ** (scale ?? currency.exponent);
      const amount = Math.round(float * factor);
    
      return dinero({ amount, currency, scale });
    }