Skip to content

Commit

Permalink
Fixed #7405, small numbers in exponential notation were wrongly inter…
Browse files Browse the repository at this point in the history
…preting decimals.
  • Loading branch information
KacperMadej authored and TorsteinHonsi committed Nov 21, 2017
1 parent 2ba2549 commit f613fe7
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 5 deletions.
27 changes: 23 additions & 4 deletions js/parts/Utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -1418,17 +1418,36 @@ H.numberFormat = function (number, decimals, decimalPoint, thousandsSep) {
thousands,
ret,
roundedNumber,
exponent = number.toString().split('e');
exponent = number.toString().split('e'),
fractionDigits;

if (decimals === -1) {
// Preserve decimals. Not huge numbers (#3793).
decimals = Math.min(origDec, 20);
} else if (!H.isNumber(decimals)) {
decimals = 2;
} else if (decimals && exponent[1] && origDec - exponent[1] > decimals) {
} else if (decimals && exponent[1] && exponent[1] < 0) {
// Expose decimals from exponential notation (#7042)
exponent[0] *= Math.pow(10, exponent[1] - decimals);
exponent[1] = decimals;
fractionDigits = decimals + +exponent[1];
if (fractionDigits >= 0) {
// remove too small part of the number while keeping the notation
exponent[0] = (+exponent[0]).toExponential(fractionDigits)
.split('e')[0];
decimals = fractionDigits;
} else {
// fractionDigits < 0
exponent[0] = exponent[0].split('.')[0] || 0;

if (decimals < 20) {
// use number instead of exponential notation (#7405)
number = (exponent[0] * Math.pow(10, exponent[1]))
.toFixed(decimals);
} else {
// or zero
number = 0;
}
exponent[1] = 0;
}
}

// Add another decimal to avoid rounding errors of float numbers. (#4573)
Expand Down
22 changes: 21 additions & 1 deletion samples/unit-tests/utilities/utilities/demo.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@
* Test number formatting
*/
QUnit.test('NumberFormat', function (assert) {
var i;

assertEquals(assert, 'Integer with decimals', "1.00", numberFormat(1, 2));
assertEquals(assert, 'Integer with decimal point', "1,0", numberFormat(1, 1, ','));
Expand Down Expand Up @@ -261,9 +262,28 @@
assertEquals(
assert,
'Decimals limit with exponential (#7042)',
"0.00",
'0.00',
numberFormat(1.5e-9, 2)
);

// small numbers with set decimals (#7405)
for (i = 7; i < 11; i++) {
assertEquals(
assert,
'Decimals = ' + i + ' - precision to ' + i + 'th digit after .',
['0.0000000', '0.00000000', '2e-9', '1.9e-9'][i - 7],
numberFormat(1.9e-9, i)
);
}

for (i = 6; i < 10; i++) {
assertEquals(
assert,
'Decimals = ' + i + ' - precision to ' + i + 'th digit after .',
['0.000001', '6e-7', '6.3e-7', '6.26e-7'][i - 6],
numberFormat(6.26e-7, i)
);
}
});


Expand Down

0 comments on commit f613fe7

Please sign in to comment.