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

toFormat

TOutput

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.

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"