// From any currency, to any currency:
fx.convert(12.99, {from: "GBP", to: "HKD"});

// Chaining sugar:
fx(1000).from("USD").to("GBP");
fx(1000).to("AED");

// With simple settings and defaults, making this possible:
fx.convert(5318008);
fx(5318008).to("AED");

// Can also be used as a nodeJS/npm or requireJS/AMD module
var fx = require("money");
require(["money"], function(fx) { /* ... */ });

// Read more below or jump to the downloads, demo playground or documentation
// maintained by openexchangerates.org

 

Introduction

Tired of trying to adapt those 10-year-old "FREE Currency Converter JavaScripts!" into something workable for your enterprise software or shopping cart? money.js is a simple library with one function: to convert a money value from any currency to any other currency.

Read on for some background information, or jump straight to the downloads, demo playground or documentation.

In order to perform currency conversion in JavaScript, you'll need a reliable source of real-time exchange rates. Open Exchange Rates uses algorithmic blending to calculate a consistently accurate and unbiased set of rates for 165+ world currencies, and provides these via a seamless API to startups, businesses and Fortune 500s, costing 10-20x less than other industry providers (and the only API to offer a Forever Free plan).

While we recommend this for all users, money.js is not tied to any particular data source - see the documentation to integrate the Open Exchange Rates API data (or any exchange rate data source) with the library in only a few lines of code.

You only need the conversion rates relative to any single currency, in order to be able to convert values between any other two currencies; money.js does it all for you.

Downloads

These links always point to the latest stable version of money.js:

»  money.js development version (4.3 kb)

»  money.min.js production/minified version (1.1 kb)

There are more download options available on the GitHub repository, at openexchangerates/money.js.

Demo Playground

You can use this JavaScript Sandbox to kick the tires and play around with money.js. It's running in a separate (sandboxed) scope, but you have access to jQuery ($), underscore (_), accounting.js (accounting) and money.js (fx).

You can use :load script.js to load extra libraries, or try :help if stuck.

Exchange rates should be set up already (defaults = from: "USD", to: "GBP") but if not, try refreshing the page. There are some sample commands to try out below.

sandbox console loading...
Some sample commands to get you started:

Interested in putting the sandbox on your JavaScript library homepage? It's on GitHub at openexchangerates/javascript-sandbox-console.

Documentation

Basic Installation

To use money.js as a standalone library, download the minified or development version of money.js, and include it in your HTML page:

<script src="path/to/money.js"></script>

You'll need to do one more thing before you can use it, which is:

Setting up exchange rates with fx.rates

To use money.js to convert currencies, you'll need to feed it with some exchange rate data and provide a base currency. (As long as you have exchange rates for every currency relative to one single other ('base') currency, money.js can convert between any other two)

The library doesn't specify a format for currency names/codes (we recommend sticking to the standard three-letter codes). It also does not mind how accurate they are, or which currency is your base rate.

Rates are stored in the fx.rates object, while the base currency is stored in fx.base. The base currency must also appear in the rates object. They should like this:

fx.base = "USD";
fx.rates = {
	"EUR" : 0.745101, // eg. 1 USD === 0.745101 EUR
	"GBP" : 0.647710, // etc...
	"HKD" : 7.781919,
	"USD" : 1,        // always include the base rate (1:1)
	/* etc */
}

You can include as many or as few currencies as you need, and the rates can be approximate, historical or just plain wrong (though we recommend sticking with up-to-date, accurate data from a reliable exchange rates API.)

Always include the base rate (the currency code from fx.base) in fx.rates object, for example "USD" : 1, so that money.js can use it for calculation.

The latest rates from the Open Exchange Rates API are delivered as JSON in the required object format, ready to feed into money.js directly. You'll need to sign up for an App ID, and you can choose whichever option you need (there is a generous Forever Free plan.)

Using the Open Exchange Rates API as an example, here we load them in via AJAX using jQuery:

<script type="text/javascript">
    // Load exchange rates data via AJAX:
    $.getJSON(
    	// NB: using Open Exchange Rates here, but you can use any source!
        'https://openexchangerates.org/api/latest.json?app_id=[YOUR APP ID]',
        function(data) {
            // Check money.js has finished loading:
            if ( typeof fx !== "undefined" && fx.rates ) {
                fx.rates = data.rates;
                fx.base = data.base;
            } else {
                // If not, apply to fxSetup global:
                var fxSetup = {
                    rates : data.rates,
                    base : data.base
                }
            }
        }
    );
</script>

You'll need to wait until the AJAX request has completed before you can begin processing conversions. You may also wish to cache approximate/historical rates on your server and bootstrap them inline into the HTML as a backup.

If bootstrapping rates into your HTML page directly, they would need to come after the script is loaded and look like this:

<script>
    fx.rates = {
    	GBP: 0.6,
    	USD: 1
    };
    fx.base = USD;
</script>';

There are more examples and methods of grabbing the latest (and historical) data, for all the most common languages and frameworks, is the Open Exchange Rates documentation.

Whichever API or data source you use, make sure that there is a base currency specified and that the exchange rates are in the object format shown above.

fx.settings and fxSetup

Use fx.settings to set default from and to currencies (optional) after the library has loaded. If you want or need to set these before the library has loaded, create a global object called fxSetup, with the same properties:

// Using `fx.settings` (must be after loading the library)
fx.settings = {
	from : "GBP",
	to : "AED"
};

// Using `fxSetup` (must be before loading the library; see note)
var fxSetup = {
	from : "GBP",
	to : "AED"
};

Note about using fxSetup: If using fxSetup, the variable needs to be available to the library (in scope) - use window.fxSetup if needed. Also note that the fxSetup method won't work if using money.js as an AMD / CommonJS module, because it won't have access to outside variables (use fx.settings for such cases).

You can also use fxSetup to load in the exchange rates and base currency before loading the library, like so:

// Adding exchange rates and base currency to `fxSetup`:
var fxSetup = {
	from : "GBP",
	to : "AED",
	base : "USD",
	rates : {
		"AED" : 3.672905
		/* etc. */
	}
};

fx.convert(val, [opts])

The basic function of the library - converts a value from one currency to another. Uses the default from and to currencies in fx.settings, or those given in opts:

// Using defaults:
fx.settings = { from: "USD", to: "GBP" };
fx.convert(1000); // 647.71034

// With options:
fx.convert(1000, {to: "HKD"}); // 7781.91949 (default `from` currency)
fx.convert(1000, {from: "GBP", to: "HKD"}); // 12014.50549

fx.convert can convert from any currency to any currency, provided they're both in the fx.rates object. For example, if all rates are relative to USD (1:1), and you have the rate for USD:GBP and USD:HKD, you can specify {from: "GBP", to: "HKD"} - money.js will calculate the relative rate between the two currencies.

Currency names

Currency names directly reference entries in the fx.rates object, so you're not limited to using the standard 3-letter currency codes. If your exchange rates data source provides pounds (£) as "British Pounds Sterling", and you pass this directly into the rates object, you could use this instead of "GBP".

If you pass in a currency in from or to for which you don't have an exchange rate, money.js will throw an error to let you know that the rate wasn't found.

Pro Tip:

We recommend informing your users that exchange rates and currency conversion are for informational purposes only.

fx.noConflict() available in standalone mode (not AMD/CJS)

The library's reference - fx - is a fairly common namespace (think animation), which may clash with other scripts. For this case, money.js stores a reference to the previous global value of fx, if any, in case you need to restore it.

If you're using another library that creates a global fx object or function, you can use fx.noConflict to restore that library's original value and also assign the money.js library object to another variable. For example:

// Some other `fx` library:
var fx = someOtherFxLibrary;

// Assign the money.js library to a global money object:
var money = fx.noConflict();

// `fx` is now back to whatever it was before money.js was loaded, and you
// can use the library via the `money` reference, like so:
money.convert(5318008);
money.settings.from = "JPY";
money(5318008).to("HKD");

Chaining with fx(val)

money.js provides basic 'chaining' (i.e. connecting method calls together, with each acting on the value returned by the previous.)

This allows a more expressive, human-readable way of writing code, while the underlying functions are exactly the same. The methods are as follows:

fx() returns a 'wrapped' fx object with a value ready for chaining (does not perform any conversion)
fx(16288) // (fxWrapper)

// NB: if parameter is a currency string, fx() will attempt to parse it to extract the
// `from` currency and `value` - so this is the same as the following example:
fx("$16288 HKD") // (fxWrapper)
.from() returns a wrapped fx object, with the value converted from default base to from currency, and ready for conversion to another:
fx(16288).from("HKD") // (fxWrapper)
.to() takes a wrapped fx object (as above) and converts the value to target currency:
fx(16288).to("GBP"); // 10549.906083 (uses default `from` currency)
fx(16288).from("AED").to("GBP"); // 2872.359629
.convert() takes a wrapped fx object and performs fx.convert(val, [opts]) on it:
fx(16288).convert(); // uses default `from` / `to` currencies
fx(16288).convert({ from:"HKD", to:"GBP" }); // 1355.694581

Integration with accounting.js

money.js works great with accounting.js - a standalone JavaScript library that provides reliable localisation and formatting of money and currency. A few examples:

var value = accounting.unformat(someNumber); // clean up number (eg. user input)
var target = "GBP"; // or some user input
var convertedValue = fx(value).from("USD").to(target);

accounting.formatMoney(convertedValue, {
	symbol: target,
	format: "%v %s"
}); // eg. "53,180.08 GBP"

This is a good idea when you're displaying currencies - values converted through money.js may have high precision (eg. 12 decimal places) depending on the rates and input value. accounting.js takes care of all the formatting for you, and also correctly rounds values as currency, as shown below with the toFixed() method:

// accounting.toFixed() is a replacement for (Number).toFixed():
(0.615).toFixed(2);           // "0.61" <== standard JavaScript
accounting.toFixed(0.615, 2); // "0.62" <== better

Usage in nodeJS / npm

money.js can easily be used inside nodeJS or any other module loader:

var fx = require("/path/to/money");
// Now load in your exchange rates and create `fx.settings` if needed

We recommend the exchange-rates npm module to make loading rates quick and easy.

You may also install the module via npm install money and reference it like this:

var fx = require("money");

Usage as a RequireJS/AMD module

money.js exposes itself as an AMD module, for script loaders such as RequireJS:

// Usage as a dependency:
require(["path/to/money"], function(fx) {
	// Now you have a well-scoped `fx` object to use
	fx.convert(5318008);
});

You'll need to set up money.js inside the callback function, with fx.rates, fx.base and (optionally) fx.settings - once those are set up, they'll also be set up anywhere else you use fx.

Summary

That's all you need to know to get started. Summary: use fx.rates and fx.base for setup. Your basic function is fx.convert(val, [opts]), which can be written like this: fx(val).from("USD").to("GBP") or in several other ways.

Links

money.js is open source and maintained by Open Exchange Rates - the lightweight currency data API for developers, startups and Fortune 500s.

Feedback, support or questions? Contact Open Exchange Rates for guidance.

Bugs, issues, suggestions or contributions? Please post them here.

money.js works great with accounting.js - the tiny standalone JavaScript number and currency formatting library, for web & nodeJS