From 0ee8427386e612b00db2c7dded4b922eaf0bf605 Mon Sep 17 00:00:00 2001 From: "Grot (@grafanabot)" <43478413+grafanabot@users.noreply.github.com> Date: Thu, 5 Nov 2020 15:29:41 +0530 Subject: [PATCH] Units: added support to handle negative fractional numbers. (#28849) (#28851) (cherry picked from commit abe96f4f898d72f868e3d04d6f21426330cfb188) Co-authored-by: Marcus Andersson --- .../src/field/displayProcessor.test.ts | 20 ++++++++++++++++++- .../src/field/displayProcessor.ts | 2 +- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/packages/grafana-data/src/field/displayProcessor.test.ts b/packages/grafana-data/src/field/displayProcessor.test.ts index 9d7c4b5f998..7876087832b 100644 --- a/packages/grafana-data/src/field/displayProcessor.test.ts +++ b/packages/grafana-data/src/field/displayProcessor.test.ts @@ -1,4 +1,4 @@ -import { getDisplayProcessor, getRawDisplayProcessor } from './displayProcessor'; +import { getDecimalsForValue, getDisplayProcessor, getRawDisplayProcessor } from './displayProcessor'; import { DisplayProcessor, DisplayValue } from '../types/displayValue'; import { MappingType, ValueMapping } from '../types/valueMapping'; import { FieldConfig, FieldType, ThresholdsMode } from '../types'; @@ -329,3 +329,21 @@ describe('getRawDisplayProcessor', () => { expect(result).toEqual({ text: expected, numeric: null }); }); }); + +describe('getDecimalsForValue', () => { + it.each` + value | expected + ${0} | ${0} + ${13.37} | ${0} + ${-13.37} | ${0} + ${12679.3712345811212} | ${0} + ${-12679.3712345811212} | ${0} + ${0.3712345} | ${2} + ${-0.37123458} | ${2} + ${-0.04671994403853774} | ${3} + ${0.04671994403853774} | ${3} + `('should return correct suggested decimal count', ({ value, expected }) => { + const result = getDecimalsForValue(value); + expect(result.decimals).toEqual(expected); + }); +}); diff --git a/packages/grafana-data/src/field/displayProcessor.ts b/packages/grafana-data/src/field/displayProcessor.ts index 66705096ebf..e7c5c45cf54 100644 --- a/packages/grafana-data/src/field/displayProcessor.ts +++ b/packages/grafana-data/src/field/displayProcessor.ts @@ -143,7 +143,7 @@ export function getDecimalsForValue(value: number, decimalOverride?: DecimalCoun return { decimals: decimalOverride, scaledDecimals: null }; } - let dec = -Math.floor(Math.log(value) / Math.LN10) + 1; + let dec = -Math.floor(Math.log(Math.abs(value)) / Math.LN10) + 1; const magn = Math.pow(10, -dec); const norm = value / magn; // norm is between 1.0 and 10.0 let size;