Skip to content

Commit aa27da2

Browse files
committed
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 angular#7870
1 parent 2f0a448 commit aa27da2

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

src/ng/filter/filters.js

+20-6
Original file line numberDiff line numberDiff line change
@@ -139,17 +139,31 @@ function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
139139

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

143144
// determine fractionSize if it is not specified
144145
if (isUndefined(fractionSize)) {
145146
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
146147
}
147-
148-
var pow = Math.pow(10, fractionSize + 1);
149-
number = Math.floor(number * pow + 5) / pow;
150-
var fraction = ('' + number).split(DECIMAL_SEP);
151-
var whole = fraction[0];
152-
fraction = fraction[1] || '';
148+
if (fractionLen > fractionSize) {
149+
raw = ('0' + numStr.replace(/\./, '')).split('');
150+
for (var i = raw.length + fractionSize - fractionLen, inc = raw[i] >= '5'; inc; --i) {
151+
if (raw[i - 1] === '9') {
152+
raw[i - 1] = '0';
153+
} else {
154+
raw[i - 1] = String.fromCharCode(raw[i - 1].charCodeAt(0) + 1);
155+
inc = false;
156+
};
157+
}
158+
raw = raw.join('');
159+
if (raw[0] === '0') raw = raw.substring(1);
160+
whole = raw.substring(0, raw.length - fractionLen);
161+
fraction = raw.substring(raw.length - fractionLen, raw.length - fractionLen + fractionSize);
162+
} else {
163+
raw = numStr.split(DECIMAL_SEP);
164+
whole = raw[0];
165+
fraction = raw[1] || '';
166+
}
153167

154168
var i, pos = 0,
155169
lgroup = pattern.lgSize,

test/ng/filter/filtersSpec.js

+5
Original file line numberDiff line numberDiff line change
@@ -147,13 +147,18 @@ describe('filters', function() {
147147
expect(number(.99, 2)).toEqual("0.99");
148148
expect(number(.999, 3)).toEqual("0.999");
149149
expect(number(.9999, 3)).toEqual("1.000");
150+
expect(number(1.9, 2)).toEqual("1.90");
151+
expect(number(1.99, 2)).toEqual("1.99");
152+
expect(number(1.999, 3)).toEqual("1.999");
153+
expect(number(1.9999, 3)).toEqual("2.000");
150154
expect(number(1234.567, 0)).toEqual("1,235");
151155
expect(number(1234.567, 1)).toEqual("1,234.6");
152156
expect(number(1234.567, 2)).toEqual("1,234.57");
153157
expect(number(1.255, 0)).toEqual("1");
154158
expect(number(1.255, 1)).toEqual("1.3");
155159
expect(number(1.255, 2)).toEqual("1.26");
156160
expect(number(1.255, 3)).toEqual("1.255");
161+
expect(number(0, 8)).toEqual("0.00000000");
157162
});
158163

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

0 commit comments

Comments
 (0)