The Currency extension provides a simple API for currency conversion.
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 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");
Loads exchange rate information
UsefulJS.Currency.load(base, rates)
base
Stringrates
Objectbase
.Returns Object: a bound instance of UsefulJS.Currency, used for chaining.
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, ... } }
Converts a value from one unit to another
UsefulJS.Currency.convert(value[, from[, to]])
value
Numberfrom
String (optional)base
.to
String (optional)base
.Returns Number: the converted value
Throws TypeError: value
is not a finite number;
RangeError: no rate information is available for from
or
to
.
Loads a value for conversion.
UsefulJS.Currency.cnv(value)
value
NumberReturns Object: a bound instance of UsefulJS.Currency, used for chaining.
The value passed in is stored for future method calls.
UsefulJS.Currency.load("EUR", ...).cnv(1000); var dollarValue = UsefulJS.Currency.to("USD"), poundValue = UsefulJS.Currency.to("GBP");
Loads a unit for conversion.
UsefulJS.Currency.from([unit])
unit
String (optional)base
.Returns Object: a bound instance of UsefulJS.Currency, used for chaining.
The value passed in is stored for future method calls.
UsefulJS.Currency.load("EUR", ...).from("GBP"); var thousandPoundsInEuros = UsefulJS.Currency.cnv(1000).to(), millionPoundsInEuros = UsefulJS.Currency.cnv(1000000).to();
Performs the conversion.
UsefulJS.Currency.to([unit])
unit
String (optional)base
.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.