Skip to content

Latest commit

 

History

History
88 lines (56 loc) · 2.3 KB

convert.mdx

File metadata and controls

88 lines (56 loc) · 2.3 KB
title description returns
convert
Create a Dinero object converter.
Dinero<TAmount>

Convert a Dinero object from a currency to another.

If you need to use fractional rates, you shouldn't use floats, but scaled amounts instead. For example, instead of passing 0.89, you should pass { amount: 89, scale: 2 }. When using scaled amounts, the function converts the returned object to the safest scale.

Parameters

The Dinero object to convert.

The currency to convert into.

The rates to convert with.

Code examples

Convert to another currency

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

const rates = { EUR: { amount: 89, scale: 2 } };
const d = dinero({ amount: 500, currency: USD });

convert(d, EUR, rates); // a Dinero object with amount 44500 and scale 4

Convert to a currency with a different scale

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

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

convert(d, IQD, rates); // a Dinero object with amount 5995000 and scale 3

Build a reusable converter

If you're converting many objects, you might want to reuse the same rates without having to pass them every time. To do so, you can wrap convert in a converter function that accepts a Dinero object and a new currency, and returns it formatted using a predefined converter.

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

function converter(dineroObject, newCurrency) {
  return convert(dineroObject, newCurrency, { EUR: { amount: 89, scale: 2 } });
}

const converter = createConverter(rates);

converter(d, EUR); // a Dinero object with amount 44500 and scale 4

You can even build your own reusable higher-order function to build converters.

// ...

function createConverter(rates) {
  return function converter(dineroObject, newCurrency) {
    return convert(dineroObject, newCurrency, rates);
  };
}