Skip to content

Commit

Permalink
fix multiply with precision, fixes #76
Browse files Browse the repository at this point in the history
  • Loading branch information
scurker committed Dec 28, 2017
1 parent 62517ed commit 8b5850f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
8 changes: 5 additions & 3 deletions src/currency.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ const defaults = {
precision: 2
};

const pow = p => Math.pow(10, p);

const regex = {
groupedNumbers: /(\d)(?=(\d{3})+\b)/g,
lastDecimal: /\.(\d+)$/
Expand All @@ -25,7 +27,7 @@ function currency(value, opts) {
}

let settings = Object.assign({}, defaults, opts)
, precision = Math.pow(10, settings.precision)
, precision = pow(settings.precision)
, v = parse(value, settings);

that.intValue = v;
Expand All @@ -39,7 +41,7 @@ function currency(value, opts) {
function parse(value, opts, round = true) {
let v = 0
, { decimal, errorOnInvalid, precision: decimals } = opts
, precision = Math.pow(10, decimals);
, precision = pow(decimals);

if (typeof value === 'number') {
v = value * precision;
Expand Down Expand Up @@ -95,7 +97,7 @@ currency.prototype = {
*/
multiply(number) {
let { intValue, _settings } = this;
return currency((intValue *= parse(number, _settings, false)) / Math.pow(10, _settings.precision + 2), _settings);
return currency((intValue *= number) / pow(_settings.precision), _settings);
},

/**
Expand Down
16 changes: 15 additions & 1 deletion test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,28 @@ test('should subtract floating point', t => {

test('currency multiplication', t => {
var value = currency(1.23).multiply(2);
t.is(parseFloat(value), 2.46, 'currency(1.23).multiplication(2) is 2.46');
var floatingValue = currency(.1).multiply(.2);

t.is(parseFloat(value), 2.46, 'currency(1.23).multiply(2) is 2.46');
t.is(parseFloat(floatingValue), .02, 'currency(.1).multiply(.2) equals 0.02');
t.not(parseFloat(floatingValue), .1*.2, 'currency(.1).multiply(.2) does not equal 0.020000000000000004');
});

test('currency multiplication with precision', t => {
var value = currency(1.369, { precision: 3 }).multiply(3);
t.is(parseFloat(value), 4.107, 'currency(1.369).multiply(3) is 4.107');
});

test('currency division', t => {
var value = currency(9.87).divide(2);
t.is(parseFloat(value), 4.93, 'currency(9.87).divide(2) is 4.93');
});

test('currency division with precision', t => {
var value = currency(4.107, { precision: 3 }).divide(3);
t.is(parseFloat(value), 1.369, 'currency(4.107).divide(3) is 1.369');
});

test('should parse negative values', t => {
var pos = currency(1.23),
neg = currency(-1.23),
Expand Down

0 comments on commit 8b5850f

Please sign in to comment.