Skip to content

Commit

Permalink
fix(numberFilter): properly format small number expressed with e nota…
Browse files Browse the repository at this point in the history
…tion

Fixes angular#10246
  • Loading branch information
pkozlowski-opensource committed Nov 27, 2014
1 parent e5a9b26 commit 6d4935f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
16 changes: 8 additions & 8 deletions src/ng/filter/filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,13 +148,13 @@ function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {

var hasExponent = false;
if (numStr.indexOf('e') !== -1) {
hasExponent = true;
var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
if (match && match[2] == '-' && match[3] > fractionSize + 1) {
if (match && match[2] == '-' && match[3] > (fractionSize || pattern.maxFrac) + 1) {
numStr = '0';
number = 0;
} else {
formatedText = numStr;
hasExponent = true;
}
}

Expand All @@ -171,10 +171,6 @@ function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);

if (number === 0) {
isNegative = false;
}

var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
Expand Down Expand Up @@ -207,12 +203,16 @@ function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {

if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
} else {

if (fractionSize > 0 && number > -1 && number < 1) {
fractionSize = isUndefined(fractionSize) ? pattern.maxFrac : fractionSize;
if (number > -1 && number < 1) {
formatedText = number.toFixed(fractionSize);
}
}

if (number === 0) {
isNegative = false;
}

parts.push(isNegative ? pattern.negPre : pattern.posPre,
formatedText,
isNegative ? pattern.negSuf : pattern.posSuf);
Expand Down
8 changes: 8 additions & 0 deletions test/ng/filter/filtersSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,14 @@ describe('filters', function() {
expect(number(-1e-6, 6)).toEqual('-0.000001');
expect(number(-1e-7, 6)).toEqual('-0.000000');
});

it('should filter exponentially small numbers when no fraction specified', function() {
expect(number(1e-10)).toEqual('0.000');
expect(number(0.0000000001)).toEqual('0.000');

expect(number(-1e-10)).toEqual('0.000');
expect(number(-0.0000000001)).toEqual('0.000');
});
});

describe('json', function() {
Expand Down

0 comments on commit 6d4935f

Please sign in to comment.