From e82645d52bcef1d74ef0edefff2cdcc1c51efcf3 Mon Sep 17 00:00:00 2001 From: Stefan Eckert Date: Fri, 7 Sep 2018 00:05:40 +0200 Subject: [PATCH] feat(formatter): optimize formatter for rounded values --- src/formatter.js | 25 +++++++++++++++---------- test/formatter.js | 3 ++- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/src/formatter.js b/src/formatter.js index ec7e5014..46627e67 100644 --- a/src/formatter.js +++ b/src/formatter.js @@ -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); @@ -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; } diff --git a/test/formatter.js b/test/formatter.js index d9074b31..c62d6281 100644 --- a/test/formatter.js +++ b/test/formatter.js @@ -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'); }); });