When working with money on the front end, comes a time when you need to display amounts on the user interface. The Dinero.js API provides functions to format Dinero objects.
import { dinero, toUnits, down } from 'dinero.js';
import { USD } from '@dinero.js/currencies';
const d = dinero({ amount: 1055, currency: USD });
toUnits(d); // [10, 55]
Copy linkDisplaying an object
The toDecimal
function exposes a pre-formatted amount in decimal format and the object's currency
. It lets you display objects the way you want using a transformer function.
import { dinero, toDecimal, toUnits } from 'dinero.js';
import { USD, MGA } from '@dinero.js/currencies';
const d1 = dinero({ amount: 5000, currency: USD });
const d2 = dinero({ amount: 13, currency: MGA });
toDecimal(d1, ({ value, currency }) => `${currency.code} ${value}`); // "USD 50.00"
toUnits(d1, ({ value }) => `${value[0]} dollars, ${value[1]} cents`); // "50 dollars, 0 cents"
toUnits(d2, ({ value }) => `${value[0]} ariary, ${value[1]} iraimbilanja`); // "2 ariary, 3 iraimbilanja"
Dinero.js uses the object's scale to determine how many decimal places to represent. You can adjust it in the transformer
.
import { dinero, toDecimal, up } from 'dinero.js';
import { USD } from '@dinero.js/currencies';
const transformer = ({ value, currency }) => {
return `${currency.code} ${Number(value).toFixed(1)}`;
};
const d = dinero({ amount: 4545, currency: USD });
toDecimal(d, transformer); // "USD 45.5"
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 write your own higher-order function to build formatters.
import { dinero, toDecimal } from 'dinero.js';
import { USD } from '@dinero.js/currencies';
// This function lets you pass a transformer and rounding options.
// It returns a function that takes a Dinero object and applies
// the closured transformer.
function createFormatter(transformer) {
return function formatter(dineroObject) {
return toDecimal(dineroObject, transformer);
};
}
// This function is reusable to format any Dinero object
// with the same transformer.
const format = createFormatter(
({ value, currency }) => `${currency.code} ${value}`
);
const d = dinero({ amount: 5000, currency: USD });
format(d); // "USD 50.00"
Copy linkRetrieving raw data
One of the most convenient formatting functions in Dinero.js is toSnapshot
. Its primary usage isn't the front end but to take snapshots of Dinero objects to inspect them.
Whenever you need to access a Dinero object's raw data, toSnapshot
is the go-to function.
import { dinero, toSnapshot } from 'dinero.js';
import { USD } from '@dinero.js/currencies';
const d = dinero({ amount: 5000, currency: USD });
toSnapshot(d);
// {
// amount: 5000,
// currency: {
// code: 'EUR',
// base: 10,
// exponent: 2,
// },
// scale: 2,
// }
Another useful usage of toSnapshot
is transport and storage. To do so, check the advanced guide on transporting and restoring.