patbenatar / change.js

A stupid simple money calculation library that deals in cents.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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.

npm version Code Climate Test Coverage

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 = require('change-js')();

Injecting dependencies

You can control how money is formatted and how decimals are rounded. For formatting, see formatMoney in accounting.js.

var Change = require('change-js')({
  formatter: accounting.formatMoney,
  rounder: Math.floor
});

Usage

Initializing

// With cents
var c2 = new Change({ cents: 1050 });

// With dollars
var c1 = new Change({ dollars: 10.5 });

Getting your dollars back

// As a float
sum.dollars();

// As formatted US dollars (requires injecting a formatter)
sum.formattedDollars();

Calculations

All calculations return new Change instances and do not mutate the original object.

var sum = c1.add(c2);
var difference = c1.subtract(c2);

var total = sum.multiply(2);
var discounted = sum.multiply(0.25);

// With a percentage, for convenience
var tax = sum.multiplyPercent(8.25);

// Chaining
var total = c1.add(c2).multiplyPercent(8.25);

Set calculations

Perform operations on lists of Change objects.

// Sum a list of Change objects
var sum = Change.sum(c1, c2, c3, c4);

// Or provide an array if you've got one
var sum = Change.sum([c1, c2, c3, c4]);

Caveats

Change.js currently only supports US dollars.

About

A stupid simple money calculation library that deals in cents.


Languages

Language:JavaScript 100.0%