simple-decimal-money
v0.2.4
Published
A module to handle currency amounts as decimals
Downloads
54
Readme
Simple Decimal Money
A module to handle currency amounts as decimals. It relies on the toFixed method and rounds the values using toFixed(rounding) after every math operation. Decimal objects are immutable.
Works only for amounts with cents and nothing more. See examples below:
Installation
npm install simple-decimal-money
API
Create an object:
import Decimal from 'simple-decimal-money';
var dc1 = new Decimal(10.334); // numeric value
var dc2 = new Decimal("10.334"); // string value
var dc3 = new Decimal(dc2) // or another Decimal
Operations
Add:
dc1.add(dc2); // returns new Decimal
dc1.add(10.10) // add numeric value, returns new Decimal
Subtract:
dc1.subtract(dc2);
Multiply:
dc1.multiply(dc2);
DivideBy:
dc1.divideBy(dc2);
Getting a number from Decimal:
dc1.toNumber()
Getting a string from Decimal:
dc1.toString() // always result of toFixed(2)
Additionally it's possible to specify another rounding precision:
var dc1 = new Decimal(10.334, 3); // numeric value
It's handy for the tax rates because they can have more than 2 decimals.
Example of price with VAT calculation:
priceVAT: function() {
var rate = new Decimal(this.get('tax.data.rate'), 3);
var price = new Decimal(this.get('price'), 3);
return price.multiply(rate.add(1)).toString();
}
The result will be rounded according to the caller object rounding property:
rate.add(1); // => rounding=3;
price.multiply(rate.add(1)) // => rounding = 3