UsefulJS.Currency

The Currency extension provides a simple API for currency conversion.

Conversion API

The conversion API can be accessed procedurally or as chained method calls. To convert from EUR to GBP, you might do this:

UsefulJS.Currency.load("EUR", { "GBP" : 0.72, ... });
var pounds = UsefulJS.Currency.convert(1000, null, "GBP"); // 720

Alternatively, you can do this:

var pounds = UsefulJS.Currency.load("EUR", { "GBP" : 0.72, ... }).cnv(1000).to("GBP");
The rates passed to load are against a base, for example USD. Assuming data is available for GBP and EUR, you can use these rates to go from USD to EUR or GBP to USD. You can also use them to go from EUR to GBP and vice-versa but this is likely to be inaccurate since GBP has its own exchange rate against the EUR that will not be the same as going via USD.

The API can be used to convert any units of the same dimension:

var myHeightInCm = UsefulJS.Currency.load("m", { feet : 3.28, cm : 100 }).cnv(6).from("feet").to("cm");

API reference

load

Loads exchange rate information

Syntax
UsefulJS.Currency.load(base, rates)
Parameters

Returns Object: a bound instance of UsefulJS.Currency, used for chaining.

Description

Exchange rates are supplied to the load function in Open Exchange Rates format, a JSON Object giving the base and the rates as follows:

{
    "base":"EUR",
    "rates":{
        "GBP:0.72,
        "USD":1.11,
        ...
    }
}

convert

Converts a value from one unit to another

Syntax
UsefulJS.Currency.convert(value[, from[, to]])
Parameters

Returns Number: the converted value

Throws TypeError: value is not a finite number; RangeError: no rate information is available for from or to.

cnv

Loads a value for conversion.

Syntax
UsefulJS.Currency.cnv(value)
Parameters

Returns Object: a bound instance of UsefulJS.Currency, used for chaining.

Description

The value passed in is stored for future method calls.

Usage
UsefulJS.Currency.load("EUR", ...).cnv(1000);
var dollarValue = UsefulJS.Currency.to("USD"),
    poundValue = UsefulJS.Currency.to("GBP");

from

Loads a unit for conversion.

Syntax
UsefulJS.Currency.from([unit])
Parameters

Returns Object: a bound instance of UsefulJS.Currency, used for chaining.

Description

The value passed in is stored for future method calls.

Usage
UsefulJS.Currency.load("EUR", ...).from("GBP");
var thousandPoundsInEuros = UsefulJS.Currency.cnv(1000).to(),
    millionPoundsInEuros = UsefulJS.Currency.cnv(1000000).to();

to

Performs the conversion.

Syntax
UsefulJS.Currency.to([unit])
Parameters

Returns Number: the converted value

Throws TypeError: the value passed to cnv was not a finite number; RangeError: no rate information is available for units passed to the from and to methods.