Skip to content

Commit

Permalink
Format scientific float (#1007)
Browse files Browse the repository at this point in the history
* modidy printFloat to check for having a certain amount of digits to force showing scientific notation
* add test cases for floats displaying properly
  • Loading branch information
jrchudy authored Mar 8, 2024
1 parent 712e2dd commit 1212606
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
16 changes: 15 additions & 1 deletion js/utils/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -1817,7 +1817,21 @@
if (options.numFracDigits) {
value = value.toFixed(options.numFracDigits); // toFixed() rounds the value, is ok?
} else {
value = value.toFixed(4);
// if the float has 13 digits or more (1 trillion or greater)
// or the float has 7 decimals or more, use scientific notation
// NOTE: javascript in browser uses 22 as the threshold for large numbers
// If there are 22 digits or more, then scientific notation is used
// ecmascript language spec: https://262.ecma-international.org/5.1/#sec-9.8.1
if (Math.abs(value) >= 1000000000000 || Math.abs(value) < 0.000001) {
// this also ensures there are more digits than the precision used
// so the number will be converted to scientific notation instead of
// being padded with zeroes with no conversion
// for example: 0.000001.toPrecision(4) ==> '0.000001000'
value = value.toPrecision(5)
} else {
value = value.toFixed(4);
}

}

// Remove leading zeroes
Expand Down
11 changes: 11 additions & 0 deletions test/specs/print_utils/tests/01.print_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@ exports.execute = function (options) {
expect(printFloat(1234.0, options)).toBe('1,234.0000');
expect(printFloat(23.0)).toBe('23.0000');
expect(printFloat(.000)).toBe('0.0000');

// scientific notation tests
expect(printFloat(100000000000)).toBe('100,000,000,000.0000');
expect(printFloat(1000000000000)).toBe('1.0000e+12');
expect(printFloat(.000001)).toBe('0.0000');
expect(printFloat(.0000001)).toBe('1.0000e-7');

expect(printFloat(1e11)).toBe('100,000,000,000.0000');
expect(printFloat(1e12)).toBe('1.0000e+12');
expect(printFloat(1e-6)).toBe('0.0000');
expect(printFloat(1e-7)).toBe('1.0000e-7');
});

it('printBoolean() should format booleans correctly.', function () {
Expand Down

0 comments on commit 1212606

Please sign in to comment.