JS Money
JS Money is a JavaScript implementation of Martin Fowlers Money pattern.
Install
The package is available through npm and bower.
$ npm install js-money
$ bower install js-money
Usage
First we need to import the library.
var Money = ;
Creating a new instance
There are multiple options of what to pass into the constructor to create a new Money instance:
- amount as number, currency as string
- amount as number, currency as object
- object with amount and currency fields (only with
fromInteger
andfromDecimal
methods)
Amounts can be supplied either as integers or decimal numbers.
Instances of Money are immutable and each arithmetic operation will return a new instance of the object.
When using decimals the library will allow only decimals with the precision allowed by the currencies smallest unit.
var fiveEur = 500 MoneyEUR;var tenDollars = Money;var someDollars = Money; // the following will fail and throw an Error since USD allows for 2 decimalsvar moreDollars = Money;// but with rounder function provider the following will workvar someMoreDollars = Money;
The currency object hold the following properties
"symbol": "$" "name": "US Dollar" "symbol_native": "$" "decimal_digits": 2 "rounding": 0 "code": "USD" "name_plural": "US dollars"
Basic arithmetics
Arithmetic operations involving multiple objects are only possible on instances with the same currency and will throw an Error otherwise.
var fiveEur = 500 MoneyEUR; // 5 EUR // addfiveEur; // 7.50 EUR // subtract fiveEur; // 0.30 EUR // multiplyfiveEur; // 6.17 EURfiveEur; // 6.18 EUR // divide fiveEur; // 2.13 EURfiveEur; // 2.14 EUR
Allocating funds
Will divide the funds based on the ratio without loosing any pennies.
var tenEur = 1000 MoneyEUR; // divide 10 EUR into 3 partsvar shares = tenEur; // returns an array of Money instances worth [334,333,333] // split 5 EUR 70/30var fiveEur = 500 MoneyEUR;var shares = fiveEur;// returns an array of money [350,150]
Comparison and equality
Two objects are equal when they are of the same amount and currency. Trying to compare 2 objects with different currencies will throw an Error.
var fiveEur = 500 MoneyEUR;var anotherFiveEur = 500 MoneyEUR;var sevenEur = 700 MoneyEUR;var fiveDollars = 500 MoneyUSD; fiveEur; // return falsefiveEur; // return true fiveEur; // return -1sevenEur; // return 1fiveEur; // return 0 fiveEur; // throw Error fiveEur; // return falsefiveEur; // return falsefiveEur; // return truefiveEur; // return true
Tests
$ npm install
$ npm test
License
Copyright (c) 2014 David Kalosi http://davidkalosi.com/