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

toFormat

string

Format a Dinero object with a custom transformer.

The transformer parameter exposes the amount in rounded units, the currency, and the initial Dinero object. The latter can be useful when formatting non-decimal currencies.

You can also specify rounding options to determine how to round the amount.

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, ({ amount, currency }) => `${currency.code} ${amount}`); // "USD 5"

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,
    ({ amount, currency }) => `${currency.code} ${amount}`
  );
}

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

format(d); // "USD 50"

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(({ amount, currency }) => {
  return `${amount.toFixed(currency.exponent).replace('.', ',')} ${
    currency.code
  }`;
});

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

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