Skip to content
This repository has been archived by the owner on Apr 12, 2024. It is now read-only.

fix(numberFilter): fix formatting error #7878

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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