From 562d96efdad8f2a034defa50209e596b217c457d Mon Sep 17 00:00:00 2001 From: "Grot (@grafanabot)" <43478413+grafanabot@users.noreply.github.com> Date: Fri, 19 Aug 2022 16:58:19 +0200 Subject: [PATCH] Decimals: Fixes auto decimals to behave the same for positive and negative values (#53960) (#53961) --- .../grafana-data/src/valueFormats/valueFormats.test.ts | 9 +++++++++ packages/grafana-data/src/valueFormats/valueFormats.ts | 5 +++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/grafana-data/src/valueFormats/valueFormats.test.ts b/packages/grafana-data/src/valueFormats/valueFormats.test.ts index e3281cc7b79..ff46f153771 100644 --- a/packages/grafana-data/src/valueFormats/valueFormats.test.ts +++ b/packages/grafana-data/src/valueFormats/valueFormats.test.ts @@ -94,6 +94,15 @@ describe('valueFormats', () => { expect(toFixed(100.4)).toBe('100'); expect(toFixed(100.5)).toBe('101'); + expect(toFixed(27.4)).toBe('27.4'); + expect(toFixed(27.5)).toBe('27.5'); + + expect(toFixed(-100)).toBe('-100'); + + expect(toFixed(-100.5)).toBe('-100'); + expect(toFixed(-100.6)).toBe('-101'); + expect(toFixed(-27.5)).toBe('-27.5'); + expect(toFixed(-27.6)).toBe('-27.6'); }); it('toFixed should handle number correctly if decimal is not null', () => { diff --git a/packages/grafana-data/src/valueFormats/valueFormats.ts b/packages/grafana-data/src/valueFormats/valueFormats.ts index 4920fe2814c..183399ebfc6 100644 --- a/packages/grafana-data/src/valueFormats/valueFormats.ts +++ b/packages/grafana-data/src/valueFormats/valueFormats.ts @@ -80,10 +80,11 @@ export function toFixed(value: number, decimals?: DecimalCount): string { } function getDecimalsForValue(value: number): number { - const log10 = Math.floor(Math.log(Math.abs(value)) / Math.LN10); + const absValue = Math.abs(value); + const log10 = Math.floor(Math.log(absValue) / Math.LN10); let dec = -log10 + 1; const magn = Math.pow(10, -dec); - const norm = value / magn; // norm is between 1.0 and 10.0 + const norm = absValue / magn; // norm is between 1.0 and 10.0 // special case for 2.5, requires an extra decimal if (norm > 2.25) {