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
Name | Type | Description | Required |
---|---|---|---|
dineroObject | Dinero<TAmount> | The Dinero object to format. | Yes |
transformer | Transformer<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.
// ...
function createFormatter(transformer) {
return function format(dineroObject) {
return toFormat(dineroObject, transformer);
};
}