Skip to content

Commit

Permalink
fix(numberFilter): correctly round fractions despite floating-point a…
Browse files Browse the repository at this point in the history
…rithmetics issues in JS

Closes angular#7870
Closes angular#7878
  • Loading branch information
IgorMinar committed Jun 24, 2014
1 parent ceaea86 commit c74bdde
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/ng/filter/filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,11 @@ function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
}

var pow = Math.pow(10, fractionSize + 1);
number = Math.floor(number * pow + 5) / pow;
// safely round numbers in JS without hitting imprecisions of floating-point arithmetics
// inspired by:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);

var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
Expand Down
5 changes: 5 additions & 0 deletions test/ng/filter/filtersSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,18 @@ describe('filters', function() {
expect(number(.99, 2)).toEqual("0.99");
expect(number(.999, 3)).toEqual("0.999");
expect(number(.9999, 3)).toEqual("1.000");
expect(number(1.9, 2)).toEqual("1.90");
expect(number(1.99, 2)).toEqual("1.99");
expect(number(1.999, 3)).toEqual("1.999");
expect(number(1.9999, 3)).toEqual("2.000");
expect(number(1234.567, 0)).toEqual("1,235");
expect(number(1234.567, 1)).toEqual("1,234.6");
expect(number(1234.567, 2)).toEqual("1,234.57");
expect(number(1.255, 0)).toEqual("1");
expect(number(1.255, 1)).toEqual("1.3");
expect(number(1.255, 2)).toEqual("1.26");
expect(number(1.255, 3)).toEqual("1.255");
expect(number(0, 8)).toEqual("0.00000000");
});

it('should filter exponentially large numbers', function() {
Expand Down

0 comments on commit c74bdde

Please sign in to comment.