Skip to content

Commit

Permalink
Fix bug with negative numbers (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
ruipneves authored and sindresorhus committed Jan 23, 2017
1 parent 105c356 commit 1b5e5d6
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 0 deletions.
4 changes: 4 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ function round(fn, x, precision) {
var exponentNeg = precision > 0 ? 'e-' : 'e';
precision = Math.abs(precision);

if (fn === 'round') {
return Number(Math.sign(x) * (Math.round(Math.abs(x) + exponent + precision) + exponentNeg + precision));
}

return Number(Math[fn](x + exponent + precision) + exponentNeg + precision);
}

Expand Down
3 changes: 3 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ test('roundTo()', t => {
t.is(fn(1.005, 2), 1.01);
t.is(fn(1.005, 0), 1);
t.is(fn(111.1, -2), 100);
t.is(fn(-0.375, 2), -0.38);
});

test('roundTo.up()', t => {
Expand All @@ -17,6 +18,7 @@ test('roundTo.up()', t => {
t.is(fn.up(1.004, 2), 1.01);
t.is(fn.up(1.111, 0), 2);
t.is(fn.up(111.1, -2), 200);
t.is(fn.up(-0.375, 2), -0.37);
});

test('roundTo.down()', t => {
Expand All @@ -26,4 +28,5 @@ test('roundTo.down()', t => {
t.is(fn.down(1.006, 2), 1.00);
t.is(fn.down(1.006, 0), 1);
t.is(fn.down(111.6, -2), 100);
t.is(fn.down(-0.375, 2), -0.38);
});

0 comments on commit 1b5e5d6

Please sign in to comment.