Change.js
Change.js is about the simplest you can get with money calculations for USD.
Initialize a Change
object with dollars or cents and add or subtract amounts or
calculate tax. All calculations are done in cents to avoid floating point
errors. All operations return the result in a new instance of Change
.
Currency formatting and rounding can be customized via dependency injection.
Setup
Requiring
Change exports a function to support injecting dependencies as arguments. When you don't want to customize anything, this just means you'll need to call it without arguments upon requiring:
var Change = ;
Injecting dependencies
You can control how money is formatted and how decimals are rounded. For
formatting, see formatMoney
in accounting.js.
var Change = formatter: accountingformatMoney rounder: Mathfloor;
Usage
Initializing
// With centsvar c2 = cents: 1050 ; // With dollarsvar c1 = dollars: 105 ;
Calculations
All calculations return new Change
instances and do not mutate the original
object.
var sum = c1;var difference = c1; var total = sum;var discounted = sum; // With a percentage, for conveniencevar tax = sum; // Chainingvar total = c1;
Getting your dollars back!
// As a floatsum; // As formatted US dollars (requires injecting a formatter)sum;
Caveats
Change.js currently only supports US dollars.