Skip to content

Commit

Permalink
feat(formatter): optimize formatter for rounded values
Browse files Browse the repository at this point in the history
  • Loading branch information
MrTelanie committed Sep 6, 2018
1 parent bc88ff1 commit e82645d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
25 changes: 15 additions & 10 deletions src/formatter.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
// https://code.open-xchange.com/#contentPanel;a7550a02-aa41-45d9-9cad-7e1c920815f3;null;ui/apps/io.ox/office/tk/utils.js;content

const MULTIPLIER = 7;

function normalizeNumber(number) {
// special handling for zero
if (number === 0) {
return { mant: 0, exp: 1 };
return { mant: 0, exp: 2 };
}

let exp = Math.floor(Math.log(Math.abs(number)) / Math.LN10);
Expand All @@ -23,21 +21,28 @@ function normalizeNumber(number) {
exp += 1;
}

for (let i = 0; i <= MULTIPLIER; i += 1) {
mant /= 10;
exp += 1;
}

return { mant, exp };
}

export default function formatNumber(nr, digits) {
const n = normalizeNumber(nr);
n.mant /= 10;
n.exp += 1;

const p = digits || 4;
const rounder = 10 ** (p + MULTIPLIER);
const rounder = 10 ** Math.max(n.exp, p);

const mant = Math.round(n.mant * rounder) / rounder;
let mant = Math.round(n.mant * rounder) / rounder;
if (mant === 1) {
mant /= 10;
n.exp += 1;
}

if (n.exp <= 1) {
mant = mant.toString().replace('0.', '');

return `0.${'0'.repeat(Math.max(0, -n.exp))}${mant}`;
}
const e = 10 ** n.exp;
return mant * e;
}
3 changes: 2 additions & 1 deletion test/formatter.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ describe('formatNumber test.', () => {
assert.equal(formatNumber(0.00009998), '0.00009998');
assert.equal(formatNumber(0.00000000000000000001), '0.00000000000000000001');
assert.equal(formatNumber(0.0000000000000000000000000001), '0.0000000000000000000000000001');
assert.equal(formatNumber(0.00009999999999), '0.0001');
assert.equal(formatNumber(0.00009999), '0.00009999');
assert.equal(formatNumber(257.5657), '257.6');
assert.equal(formatNumber(2575657546445.985), '2576000000000');
assert.equal(formatNumber(2575657546445.985), '2575657546446');
});
});

0 comments on commit e82645d

Please sign in to comment.