Click here for v1.x documentation.
Dinero.js
Dinero.js version

toFormat

string

Format a Dinero object with a custom transformer.

The function takes a transformer function which exposes useful information to format the object.

The transformer parameter exposes an object with the following properties:

  • units: the amount divided into each unit and sub-unit. It uses toUnits under the hood.
  • decimal: a stringified decimal representation of the amount, in major currency units. If the currency isn't decimal and expressed with a single base, this is undefined.
  • currency: the object's currency.
  • dineroObject: the initial Dinero object. This can be useful when formatting non-decimal currencies.

Copy linkParameters

NameTypeDescriptionRequired
dineroObjectDinero<TAmount>

The Dinero object to format.

Yes
transformerTransformer<TAmount>

A transformer function.

Yes

Copy linkCode examples

Copy linkFormat an object with the passed transformer

import { dinero, toFormat } from 'dinero.js';
import { USD } from '@dinero.js/currencies';

const d = dinero({ amount: 500, currency: USD });

toFormat(d, ({ decimal, currency }) => `${currency.code} ${decimal}`); // "USD 5.00"

Copy linkBuild a reusable formatter

If you're formatting many objects, you might want to reuse the same transformer without having to pass it every time. To do so, you can wrap toFormat in a formatter function that accepts a Dinero object and returns it formatted using a predefined formatter.

import { dinero, toFormat } from 'dinero.js';
import { USD } from '@dinero.js/currencies';

function format(dineroObject) {
  return toFormat(
    dineroObject,
    ({ decimal, currency }) => `${currency.code} ${decimal}`
  );
}

const d = dinero({ amount: 5000, currency: USD });

format(d); // "USD 50.00"

You can even build your own reusable higher-order function to build formatters. This can be useful if you need to create multiple formatters, for example to cater to multiple locales.

// ...

function createFormatter(transformer) {
  return function format(dineroObject) {
    return toFormat(dineroObject, transformer);
  };
}

const frenchFormat = createFormatter(({ decimal, currency }) => {
  return `${Number(decimal).toFixed(currency.exponent).replace('.', ',')} ${
    currency.code
  }`;
});

const americanFormat = createFormatter(({ decimal, currency }) => {
  return `${currency.code} ${Number(decimal).toFixed(currency.exponent)}`;
});

In such a situation, you can also create a single formatter based on the Internationalization API.