From 2e980d9ef1ca0384ea92b025e80b0d9b449b98de Mon Sep 17 00:00:00 2001 From: Lucas Galfaso Date: Tue, 17 Jun 2014 17:39:43 +0200 Subject: [PATCH] fix(numberFilter): fix formatting error For numbers that when converted to string do not have an exponent, do the number rounding using string manipulation Closes #7870 --- src/ng/filter/filters.js | 26 ++++++++++++++++++++------ test/ng/filter/filtersSpec.js | 5 +++++ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/ng/filter/filters.js b/src/ng/filter/filters.js index 14e71b53e266..f7b4dc396617 100644 --- a/src/ng/filter/filters.js +++ b/src/ng/filter/filters.js @@ -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, diff --git a/test/ng/filter/filtersSpec.js b/test/ng/filter/filtersSpec.js index 271691efcefa..5ed1b8a1667b 100644 --- a/test/ng/filter/filtersSpec.js +++ b/test/ng/filter/filtersSpec.js @@ -147,6 +147,10 @@ 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"); @@ -154,6 +158,7 @@ describe('filters', function() { 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() {