money-math
Advanced tools
Comparing version 1.0.0 to 1.1.0
26
money.js
@@ -71,2 +71,5 @@ (function (exports) { | ||
exports.centsToAmount = function (cents) { | ||
var sign, | ||
abs; | ||
if (!isString(cents)) { | ||
@@ -76,7 +79,10 @@ return; | ||
while (cents.length < 3) { | ||
cents = ["0", cents].join(""); | ||
sign = (cents[0] === "-" ? "-" : ""); | ||
abs = (sign === "-" ? cents.substr(1) : cents) | ||
while (abs.length < 3) { | ||
abs = ["0", abs].join(""); | ||
} | ||
return cents.substr(0, cents.length - 2) + "." + cents.substr(-2); | ||
return sign + abs.substr(0, abs.length - 2) + "." + abs.substr(-2); | ||
}; | ||
@@ -116,2 +122,16 @@ | ||
exports.div = function (a, b) { | ||
var hundredthsOfCents = bignum( | ||
exports.amountToCents(a) | ||
).mul("10000").div( | ||
exports.amountToCents(b) | ||
), | ||
remainder = parseInt(hundredthsOfCents.toString().substr(-2), 10); | ||
return exports.centsToAmount( | ||
hundredthsOfCents.div("100").add(remainder > 50 ? 1 : 0).toString() | ||
); | ||
}; | ||
exports.percent = function (value, percent) { | ||
@@ -118,0 +138,0 @@ var p = bignum(exports.amountToCents(value)).mul(exports.amountToCents(percent)), |
{ | ||
"name": "money-math", | ||
"version": "1.0.0", | ||
"version": "1.1.0", | ||
"description": "bignum-based arbitrary precision operations on currency amounts \"XXX.YY\"; because floats are BAD for representing money", | ||
@@ -5,0 +5,0 @@ "main": "money.js", |
@@ -42,2 +42,3 @@ [](http://travis-ci.org/ikr/money-math) | ||
money.mul("24.00", "0.25"); // "6.00" | ||
money.div("64.00", "2.00"); // "32.00" | ||
money.percent("200.00", "3.25"); // "6.50" | ||
@@ -44,0 +45,0 @@ |
@@ -25,2 +25,10 @@ (function () { | ||
it("works on a negative fraction", function () { | ||
expect(money.centsToAmount("-32")).toBe("-0.32"); | ||
}); | ||
it("works on a tiny negative fraction", function () { | ||
expect(money.centsToAmount("-1")).toBe("-0.01"); | ||
}); | ||
it("works for zero", function () { | ||
@@ -156,2 +164,20 @@ expect(money.centsToAmount("0")).toBe("0.00"); | ||
describe("money.div()", function () { | ||
it("basically works", function () { | ||
expect(money.div("64.00", "2.00")).toBe("32.00"); | ||
}); | ||
it("rounds stuff up 1", function () { | ||
expect(money.div("1.00", "3.00")).toBe("0.33"); | ||
}); | ||
it("rounds stuff up 2", function () { | ||
expect(money.div("0.50", "3.00")).toBe("0.17"); | ||
}); | ||
it("works for negative dividend, with rounding up", function () { | ||
expect(money.div("-1.00", "3.00")).toBe("-0.33"); | ||
}); | ||
}); | ||
describe("money.percent()", function () { | ||
@@ -158,0 +184,0 @@ it("calcualtes the [2nd argument] percent of the [1st argument] 1", function () { |
Sorry, the diff of this file is not supported yet
16430
316
63