Skip to content

Commit

Permalink
fix(numberFilter): fix formatting error
Browse files Browse the repository at this point in the history
For numbers that when converted to string do not
have an exponent, do the number rounding using string manipulation

Closes angular#7870
  • Loading branch information
lgalfaso committed Jun 17, 2014
1 parent 2f0a448 commit 2e980d9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
26 changes: 20 additions & 6 deletions src/ng/filter/filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,17 +139,31 @@ function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {

if (!hasExponent) {
var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
var whole, fraction, raw;

// determine fractionSize if it is not specified
if (isUndefined(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;
var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
if (fractionLen > fractionSize) {
raw = ('0' + numStr.replace(/\./, '')).split('');
for (var j = raw.length + fractionSize - fractionLen, inc = raw[j] >= '5'; inc; --j) {
if (raw[j - 1] === '9') {
raw[j - 1] = '0';
} else {
raw[j - 1] = String.fromCharCode(raw[j - 1].charCodeAt(0) + 1);
inc = false;
}
}
raw = raw.join('');
if (raw[0] === '0') raw = raw.substring(1);
whole = raw.substring(0, raw.length - fractionLen);
fraction = raw.substring(raw.length - fractionLen, raw.length - fractionLen + fractionSize);
} else {
raw = numStr.split(DECIMAL_SEP);
whole = raw[0];
fraction = raw[1] || '';
}

var i, pos = 0,
lgroup = pattern.lgSize,
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 2e980d9

Please sign in to comment.