Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix scientific notation #17

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
11 changes: 11 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,17 @@ function formatter(options) {
overrideOptions = overrideOptions || {};

if (number || number === 0) {
if (typeof number === 'number') {
//get rid of the possible "e-"
var parts = number.toString().split('e-');
if (parts.length === 2) {
var digits = (parts[0].replace('.', '').replace('-', '')).length - 1 + Number(parts[1]);
//maximum number of digits is 20
//see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
digits = digits > 20 ? 20 : digits;
number = number.toFixed(digits);
}
}
number = '' + number;//convert number to string if it isn't already
} else {
return '';
Expand Down
13 changes: 13 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -502,3 +502,16 @@ describe('£68,932/items with no separators', function () {
expect(formatFactory({prefix: '£', suffix: '/item'})(68932, {noSeparator: true})).to.be('£68932/item');
});
});

//scientific notation
describe('scientific notation', function() {
it('get rid of "e-"', function () {
expect(formatFactory()(1.23456e-10)).to.be('0.000000000123456');
});
it('round', function () {
expect(formatFactory({round: 2})(1.4551915228366852e-11)).to.be('0.00');
});
it('truncate', function () {
expect(formatFactory({truncate: 2})(1.29995068248398e-16)).to.be('0.00');
});
});