This is a pre-release version. Use at your own risk.
A JavaScript library for dealing with money, safely.
npm install money-money-money
const { Money } = require('money-money-money');
const money = new Money('100', 'EUR');
console.log(money.toLocaleString());
Have you ever tried to repesent the US national debt in Iranian rial?
27067291392010 USD * 42105 IRR / USD = 1139668304060581050 IRR
Many libraries would completely fail or silently lose accuracy. Not this one.
const { Money } = require('money-money-money');
const usNationalDebtUsd = new Money('27067291392010', 'USD');
const usNationalDebtIrr = usNationalDebtUsd.convertCurrency('IRR', '42105');
console.assert('1139668304060581050' === usNationalDebtIrr.toDecimalString());
console.assert('IRR' === usNationalDebtIrr.currency);
You cannot format IRR 1139668304060581050 precisely using the built-in toLocaleString
function because it relies on Intl.NumberFormat.format
which itself can only format a floating point Number
.
const { Money } = require('money-money-money');
const money = new Money('1139668304060581050', 'IRR');
money.toLocaleString(); // throws Error
If you are fine with the loss of accuracy then you can call toLocaleString
with the custom option precisionHandling
.
const { Money } = require('money-money-money');
const money = new Money('1139668304060581050', 'IRR');
console.assert('IRR\u00A01,139,668,304,060,581,000' === money.toLocaleString(undefined, { precisionHandling: 'unchecked' }));
console.assert('~\u00A0IRR\u00A01,139,668,304,060,581,000' === money.toLocaleString(undefined, { precisionHandling: 'show_imprecision' }));
This library depends on big.js for arbitrary-precision decimal arithmetic.
Additionally the environment must provide Intl.NumberFormat
. It is used to determine how many decimal places the currency uses and for formatting. Intl.NumberFormat
is supported by all major browsers and all recent Node.js versions.
Please note: By default, Node.js versions 12 and earlier are built with small-icu. This means that formatting may be unavailable for your locale. For more information see the Node.js Internationalization Support. Since Node version 13 the full-icu
is included by default.
This library is licensed under the MIT license.