Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat: allow custom precision in dashboard panels (#9054)

SagarRajput-76db74a55858a
diff --git a/frontend/src/components/Graph/__tests__/yAxisConfig.test.ts b/frontend/src/components/Graph/__tests__/yAxisConfig.test.ts
new file mode 100644
index 0000000000..b5ddb97b9f
--- /dev/null
+++ b/frontend/src/components/Graph/__tests__/yAxisConfig.test.ts
@@ -0,0 +1,371 @@
+/* eslint-disable sonarjs/no-duplicate-string */
+import { getYAxisFormattedValue, PrecisionOptionsEnum } from '../yAxisConfig';
+
+const testFullPrecisionGetYAxisFormattedValue = (
+ value: string,
+ format: string,
+): string => getYAxisFormattedValue(value, format, PrecisionOptionsEnum.FULL);
+
+describe('getYAxisFormattedValue - none (full precision legacy assertions)', () => {
+ test('large integers and decimals', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('250034', 'none')).toBe(
+ '250034',
+ );
+ expect(
+ testFullPrecisionGetYAxisFormattedValue('250034897.12345', 'none'),
+ ).toBe('250034897.12345');
+ expect(
+ testFullPrecisionGetYAxisFormattedValue('250034897.02354', 'none'),
+ ).toBe('250034897.02354');
+ expect(testFullPrecisionGetYAxisFormattedValue('9999999.9999', 'none')).toBe(
+ '9999999.9999',
+ );
+ });
+
+ test('preserves leading zeros after decimal until first non-zero', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('1.0000234', 'none')).toBe(
+ '1.0000234',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('0.00003', 'none')).toBe(
+ '0.00003',
+ );
+ });
+
+ test('trims to three significant decimals and removes trailing zeros', () => {
+ expect(
+ testFullPrecisionGetYAxisFormattedValue('0.000000250034', 'none'),
+ ).toBe('0.000000250034');
+ expect(testFullPrecisionGetYAxisFormattedValue('0.00000025', 'none')).toBe(
+ '0.00000025',
+ );
+
+ // Big precision, limiting the javascript precision (~16 digits)
+ expect(
+ testFullPrecisionGetYAxisFormattedValue('1.0000000000000001', 'none'),
+ ).toBe('1');
+ expect(
+ testFullPrecisionGetYAxisFormattedValue('1.00555555559595876', 'none'),
+ ).toBe('1.005555555595958');
+
+ expect(testFullPrecisionGetYAxisFormattedValue('0.000000001', 'none')).toBe(
+ '0.000000001',
+ );
+ expect(
+ testFullPrecisionGetYAxisFormattedValue('0.000000250000', 'none'),
+ ).toBe('0.00000025');
+ });
+
+ test('whole numbers normalize', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('1000', 'none')).toBe('1000');
+ expect(testFullPrecisionGetYAxisFormattedValue('99.5458', 'none')).toBe(
+ '99.5458',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('1.234567', 'none')).toBe(
+ '1.234567',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('99.998', 'none')).toBe(
+ '99.998',
+ );
+ });
+
+ test('strip redundant decimal zeros', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('1000.000', 'none')).toBe(
+ '1000',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('99.500', 'none')).toBe(
+ '99.5',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('1.000', 'none')).toBe('1');
+ });
+
+ test('edge values', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('0', 'none')).toBe('0');
+ expect(testFullPrecisionGetYAxisFormattedValue('-0', 'none')).toBe('0');
+ expect(testFullPrecisionGetYAxisFormattedValue('Infinity', 'none')).toBe('∞');
+ expect(testFullPrecisionGetYAxisFormattedValue('-Infinity', 'none')).toBe(
+ '-∞',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('invalid', 'none')).toBe(
+ 'NaN',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('', 'none')).toBe('NaN');
+ expect(testFullPrecisionGetYAxisFormattedValue('abc123', 'none')).toBe('NaN');
+ });
+
+ test('small decimals keep precision as-is', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('0.0001', 'none')).toBe(
+ '0.0001',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('-0.0001', 'none')).toBe(
+ '-0.0001',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('0.000000001', 'none')).toBe(
+ '0.000000001',
+ );
+ });
+
+ test('simple decimals preserved', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('0.1', 'none')).toBe('0.1');
+ expect(testFullPrecisionGetYAxisFormattedValue('0.2', 'none')).toBe('0.2');
+ expect(testFullPrecisionGetYAxisFormattedValue('0.3', 'none')).toBe('0.3');
+ expect(testFullPrecisionGetYAxisFormattedValue('1.0000000001', 'none')).toBe(
+ '1.0000000001',
+ );
+ });
+});
+
+describe('getYAxisFormattedValue - units (full precision legacy assertions)', () => {
+ test('ms', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('1500', 'ms')).toBe('1.5 s');
+ expect(testFullPrecisionGetYAxisFormattedValue('500', 'ms')).toBe('500 ms');
+ expect(testFullPrecisionGetYAxisFormattedValue('60000', 'ms')).toBe('1 min');
+ expect(testFullPrecisionGetYAxisFormattedValue('295.429', 'ms')).toBe(
+ '295.429 ms',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('4353.81', 'ms')).toBe(
+ '4.35381 s',
+ );
+ });
+
+ test('s', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('90', 's')).toBe('1.5 mins');
+ expect(testFullPrecisionGetYAxisFormattedValue('30', 's')).toBe('30 s');
+ expect(testFullPrecisionGetYAxisFormattedValue('3600', 's')).toBe('1 hour');
+ });
+
+ test('m', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('90', 'm')).toBe('1.5 hours');
+ expect(testFullPrecisionGetYAxisFormattedValue('30', 'm')).toBe('30 min');
+ expect(testFullPrecisionGetYAxisFormattedValue('1440', 'm')).toBe('1 day');
+ });
+
+ test('bytes', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('1024', 'bytes')).toBe(
+ '1 KiB',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('512', 'bytes')).toBe('512 B');
+ expect(testFullPrecisionGetYAxisFormattedValue('1536', 'bytes')).toBe(
+ '1.5 KiB',
+ );
+ });
+
+ test('mbytes', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('1024', 'mbytes')).toBe(
+ '1 GiB',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('512', 'mbytes')).toBe(
+ '512 MiB',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('1536', 'mbytes')).toBe(
+ '1.5 GiB',
+ );
+ });
+
+ test('kbytes', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('1024', 'kbytes')).toBe(
+ '1 MiB',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('512', 'kbytes')).toBe(
+ '512 KiB',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('1536', 'kbytes')).toBe(
+ '1.5 MiB',
+ );
+ });
+
+ test('short', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('1000', 'short')).toBe('1 K');
+ expect(testFullPrecisionGetYAxisFormattedValue('1500', 'short')).toBe(
+ '1.5 K',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('999', 'short')).toBe('999');
+
+ expect(testFullPrecisionGetYAxisFormattedValue('1000000', 'short')).toBe(
+ '1 Mil',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('1555600', 'short')).toBe(
+ '1.5556 Mil',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('999999', 'short')).toBe(
+ '999.999 K',
+ );
+
+ expect(testFullPrecisionGetYAxisFormattedValue('1000000000', 'short')).toBe(
+ '1 Bil',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('1500000000', 'short')).toBe(
+ '1.5 Bil',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('999999999', 'short')).toBe(
+ '999.999999 Mil',
+ );
+ });
+
+ test('percent', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('0.15', 'percent')).toBe(
+ '0.15%',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('0.1234', 'percent')).toBe(
+ '0.1234%',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('0.123499', 'percent')).toBe(
+ '0.123499%',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('1.5', 'percent')).toBe(
+ '1.5%',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('0.0001', 'percent')).toBe(
+ '0.0001%',
+ );
+ expect(
+ testFullPrecisionGetYAxisFormattedValue('0.000000001', 'percent'),
+ ).toBe('1e-9%');
+ expect(
+ testFullPrecisionGetYAxisFormattedValue('0.000000250034', 'percent'),
+ ).toBe('0.000000250034%');
+ expect(testFullPrecisionGetYAxisFormattedValue('0.00000025', 'percent')).toBe(
+ '0.00000025%',
+ );
+ // Big precision, limiting the javascript precision (~16 digits)
+ expect(
+ testFullPrecisionGetYAxisFormattedValue('1.0000000000000001', 'percent'),
+ ).toBe('1%');
+ expect(
+ testFullPrecisionGetYAxisFormattedValue('1.00555555559595876', 'percent'),
+ ).toBe('1.005555555595958%');
+ });
+
+ test('ratio', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('0.5', 'ratio')).toBe(
+ '0.5 ratio',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('1.25', 'ratio')).toBe(
+ '1.25 ratio',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('2.0', 'ratio')).toBe(
+ '2 ratio',
+ );
+ });
+
+ test('temperature units', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('25', 'celsius')).toBe(
+ '25 °C',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('0', 'celsius')).toBe('0 °C');
+ expect(testFullPrecisionGetYAxisFormattedValue('-10', 'celsius')).toBe(
+ '-10 °C',
+ );
+
+ expect(testFullPrecisionGetYAxisFormattedValue('77', 'fahrenheit')).toBe(
+ '77 °F',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('32', 'fahrenheit')).toBe(
+ '32 °F',
+ );
+ expect(testFullPrecisionGetYAxisFormattedValue('14', 'fahrenheit')).toBe(
+ '14 °F',
+ );
+ });
+
+ test('ms edge cases', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('0', 'ms')).toBe('0 ms');
+ expect(testFullPrecisionGetYAxisFormattedValue('-1500', 'ms')).toBe('-1.5 s');
+ expect(testFullPrecisionGetYAxisFormattedValue('Infinity', 'ms')).toBe('∞');
+ });
+
+ test('bytes edge cases', () => {
+ expect(testFullPrecisionGetYAxisFormattedValue('0', 'bytes')).toBe('0 B');
+ expect(testFullPrecisionGetYAxisFormattedValue('-1024', 'bytes')).toBe(
+ '-1 KiB',
+ );
+ });
+});
+
+describe('getYAxisFormattedValue - precision option tests', () => {
+ test('precision 0 drops decimal part', () => {
+ expect(getYAxisFormattedValue('1.2345', 'none', 0)).toBe('1');
+ expect(getYAxisFormattedValue('0.9999', 'none', 0)).toBe('0');
+ expect(getYAxisFormattedValue('12345.6789', 'none', 0)).toBe('12345');
+ expect(getYAxisFormattedValue('0.0000123456', 'none', 0)).toBe('0');
+ expect(getYAxisFormattedValue('1000.000', 'none', 0)).toBe('1000');
+ expect(getYAxisFormattedValue('0.000000250034', 'none', 0)).toBe('0');
+ expect(getYAxisFormattedValue('1.00555555559595876', 'none', 0)).toBe('1');
+
+ // with unit
+ expect(getYAxisFormattedValue('4353.81', 'ms', 0)).toBe('4 s');
+ });
+ test('precision 1,2,3,4 decimals', () => {
+ expect(getYAxisFormattedValue('1.2345', 'none', 1)).toBe('1.2');
+ expect(getYAxisFormattedValue('1.2345', 'none', 2)).toBe('1.23');
+ expect(getYAxisFormattedValue('1.2345', 'none', 3)).toBe('1.234');
+ expect(getYAxisFormattedValue('1.2345', 'none', 4)).toBe('1.2345');
+
+ expect(getYAxisFormattedValue('0.0000123456', 'none', 1)).toBe('0.00001');
+ expect(getYAxisFormattedValue('0.0000123456', 'none', 2)).toBe('0.000012');
+ expect(getYAxisFormattedValue('0.0000123456', 'none', 3)).toBe('0.0000123');
+ expect(getYAxisFormattedValue('0.0000123456', 'none', 4)).toBe('0.00001234');
+
+ expect(getYAxisFormattedValue('1000.000', 'none', 1)).toBe('1000');
+ expect(getYAxisFormattedValue('1000.000', 'none', 2)).toBe('1000');
+ expect(getYAxisFormattedValue('1000.000', 'none', 3)).toBe('1000');
+ expect(getYAxisFormattedValue('1000.000', 'none', 4)).toBe('1000');
+
+ expect(getYAxisFormattedValue('0.000000250034', 'none', 1)).toBe('0.0000002');
+ expect(getYAxisFormattedValue('0.000000250034', 'none', 2)).toBe(
+ '0.00000025',
+ ); // leading zeros + 2 significant => same trimmed
+ expect(getYAxisFormattedValue('0.000000250034', 'none', 3)).toBe(
+ '0.00000025',
+ );
+ expect(getYAxisFormattedValue('0.000000250304', 'none', 4)).toBe(
+ '0.0000002503',
+ );
+
+ expect(getYAxisFormattedValue('1.00555555559595876', 'none', 1)).toBe(
+ '1.005',
+ );
+ expect(getYAxisFormattedValue('1.00555555559595876', 'none', 2)).toBe(
+ '1.0055',
+ );
+ expect(getYAxisFormattedValue('1.00555555559595876', 'none', 3)).toBe(
+ '1.00555',
+ );
+ expect(getYAxisFormattedValue('1.00555555559595876', 'none', 4)).toBe(
+ '1.005555',
+ );
+
+ // with unit
+ expect(getYAxisFormattedValue('4353.81', 'ms', 1)).toBe('4.4 s');
+ expect(getYAxisFormattedValue('4353.81', 'ms', 2)).toBe('4.35 s');
+ expect(getYAxisFormattedValue('4353.81', 'ms', 3)).toBe('4.354 s');
+ expect(getYAxisFormattedValue('4353.81', 'ms', 4)).toBe('4.3538 s');
+
+ // Percentages
+ expect(getYAxisFormattedValue('0.123456', 'percent', 2)).toBe('0.12%');
+ expect(getYAxisFormattedValue('0.123456', 'percent', 4)).toBe('0.1235%'); // approximation
+ });
+
+ test('precision full uses up to DEFAULT_SIGNIFICANT_DIGITS significant digits', () => {
+ expect(
+ getYAxisFormattedValue(
+ '0.00002625429914148441',
+ 'none',
+ PrecisionOptionsEnum.FULL,
+ ),
+ ).toBe('0.000026254299141');
+ expect(
+ getYAxisFormattedValue(
+ '0.000026254299141484417',
+ 's',
+ PrecisionOptionsEnum.FULL,
+ ),
+ ).toBe('26254299141484417000000 µs');
+
+ expect(
+ getYAxisFormattedValue('4353.81', 'ms', PrecisionOptionsEnum.FULL),
+ ).toBe('4.35381 s');
+ expect(getYAxisFormattedValue('500', 'ms', PrecisionOptionsEnum.FULL)).toBe(
+ '500 ms',
+ );
+ });
+});
diff --git a/frontend/src/components/Graph/yAxisConfig.ts b/frontend/src/components/Graph/yAxisConfig.ts
index a5eca12926..e5d6feafac 100644
--- a/frontend/src/components/Graph/yAxisConfig.ts
+++ b/frontend/src/components/Graph/yAxisConfig.ts
@@ -1,58 +1,158 @@
+/* eslint-disable sonarjs/cognitive-complexity */
import { formattedValueToString, getValueFormat } from '@grafana/data';
+import * as Sentry from '@sentry/react';
+import { isNaN } from 'lodash-es';
+const DEFAULT_SIGNIFICANT_DIGITS = 15;
+// max decimals to keep should not exceed 15 decimal places to avoid floating point precision issues
+const MAX_DECIMALS = 15;
+
+export enum PrecisionOptionsEnum {
+ ZERO = 0,
+ ONE = 1,
+ TWO = 2,
+ THREE = 3,
+ FOUR = 4,
+ FULL = 'full',
+}
+export type PrecisionOption = 0 | 1 | 2 | 3 | 4 | PrecisionOptionsEnum.FULL;
+
+/**
+ * Formats a number for display, preserving leading zeros after the decimal point
+ * and showing up to DEFAULT_SIGNIFICANT_DIGITS digits after the first non-zero decimal digit.
+ * It avoids scientific notation and removes unnecessary trailing zeros.
+ *
+ * @example
+ * formatDecimalWithLeadingZeros(1.2345); // "1.2345"
+ * formatDecimalWithLeadingZeros(0.0012345); // "0.0012345"
+ * formatDecimalWithLeadingZeros(5.0); // "5"
+ *
+ * @param value The number to format.
+ * @returns The formatted string.
+ */
+const formatDecimalWithLeadingZeros = (
+ value: number,
+ precision: PrecisionOption,
+): string => {
+ if (value === 0) {
+ return '0';
+ }
+
+ // Use toLocaleString to get a full decimal representation without scientific notation.
+ const numStr = value.toLocaleString('en-US', {
+ useGrouping: false,
+ maximumFractionDigits: 20,
+ });
+
+ const [integerPart, decimalPart = ''] = numStr.split('.');
+
+ // If there's no decimal part, the integer part is the result.
+ if (!decimalPart) {
+ return integerPart;
+ }
+
+ // Find the index of the first non-zero digit in the decimal part.
+ const firstNonZeroIndex = decimalPart.search(/[^0]/);
+
+ // If the decimal part consists only of zeros, return just the integer part.
+ if (firstNonZeroIndex === -1) {
+ return integerPart;
+ }
+
+ // Determine the number of decimals to keep: leading zeros + up to N significant digits.
+ const significantDigits =
+ precision === PrecisionOptionsEnum.FULL
+ ? DEFAULT_SIGNIFICANT_DIGITS
+ : precision;
+ const decimalsToKeep = firstNonZeroIndex + (significantDigits || 0);
+
+ // max decimals to keep should not exceed 15 decimal places to avoid floating point precision issues
+ const finalDecimalsToKeep = Math.min(decimalsToKeep, MAX_DECIMALS);
+ const trimmedDecimalPart = decimalPart.substring(0, finalDecimalsToKeep);
+
+ // If precision is 0, we drop the decimal part entirely.
+ if (precision === 0) {
+ return integerPart;
+ }
+
+ // Remove any trailing zeros from the result to keep it clean.
+ const finalDecimalPart = trimmedDecimalPart.replace(/0+$/, '');
+
+ // Return the integer part, or the integer and decimal parts combined.
+ return finalDecimalPart ? `${integerPart}.${finalDecimalPart}` : integerPart;
+};
+
+/**
+ * Formats a Y-axis value based on a given format string.
+ *
+ * @param value The string value from the axis.
+ * @param format The format identifier (e.g. 'none', 'ms', 'bytes', 'short').
+ * @returns A formatted string ready for display.
+ */
export const getYAxisFormattedValue = (
value: string,
format: string,
+ precision: PrecisionOption = 2, // default precision requested
): string => {
- let decimalPrecision: number | undefined;
- const parsedValue = getValueFormat(format)(
- parseFloat(value),
- undefined,
- undefined,
- undefined,
- );
- try {
- const decimalSplitted = parsedValue.text.split('.');
- if (decimalSplitted.length === 1) {
- decimalPrecision = 0;
- } else {
- const decimalDigits = decimalSplitted[1].split('');
- decimalPrecision = decimalDigits.length;
- let nonZeroCtr = 0;
- for (let idx = 0; idx < decimalDigits.length; idx += 1) {
- if (decimalDigits[idx] !== '0') {
- nonZeroCtr += 1;
- if (nonZeroCtr >= 2) {
- decimalPrecision = idx + 1;
- }
- } else if (nonZeroCtr) {
- decimalPrecision = idx;
- break;
- }
- }
- }
+ const numValue = parseFloat(value);
- return formattedValueToString(
- getValueFormat(format)(
- parseFloat(value),
- decimalPrecision,
- undefined,
- undefined,
- ),
- );
- } catch (error) {
- console.error(error);
+ // Handle non-numeric or special values first.
+ if (isNaN(numValue)) return 'NaN';
+ if (numValue === Infinity) return '∞';
+ if (numValue === -Infinity) return '-∞';
+
+ const decimalPlaces = value.split('.')[1]?.length || undefined;
+
+ // Use custom formatter for the 'none' format honoring precision
+ if (format === 'none') {
+ return formatDecimalWithLeadingZeros(numValue, precision);
}
- return `${parseFloat(value)}`;
-};
-export const getToolTipValue = (value: string, format?: string): string => {
+ // For all other standard formats, delegate to grafana/data's built-in formatter.
+ const computeDecimals = (): number | undefined => {
+ if (precision === PrecisionOptionsEnum.FULL) {
+ return decimalPlaces && decimalPlaces >= DEFAULT_SIGNIFICANT_DIGITS
+ ? decimalPlaces
+ : DEFAULT_SIGNIFICANT_DIGITS;
+ }
+ return precision;
+ };
+
+ const fallbackFormat = (): string => {
+ if (precision === PrecisionOptionsEnum.FULL) return numValue.toString();
+ if (precision === 0) return Math.round(numValue).toString();
+ return precision !== undefined
+ ? numValue
+ .toFixed(precision)
+ .replace(/(\.[0-9]*[1-9])0+$/, '$1') // trimming zeros
+ .replace(/\.$/, '')
+ : numValue.toString();
+ };
+
try {
- return formattedValueToString(
- getValueFormat(format)(parseFloat(value), undefined, undefined, undefined),
- );
+ const formatter = getValueFormat(format);
+ const formattedValue = formatter(numValue, computeDecimals(), undefined);
+ if (formattedValue.text && formattedValue.text.includes('.')) {
+ formattedValue.text = formatDecimalWithLeadingZeros(
+ parseFloat(formattedValue.text),
+ precision,
+ );
+ }
+ return formattedValueToString(formattedValue);
} catch (error) {
- console.error(error);
+ Sentry.captureEvent({
+ message: `Error applying formatter: ${
+ error instanceof Error ? error.message : 'Unknown error'
+ }`,
+ level: 'error',
+ });
+ return fallbackFormat();
}
- return `${value}`;
};
+
+export const getToolTipValue = (
+ value: string | number,
+ format?: string,
+ precision?: PrecisionOption,
+): string =>
+ getYAxisFormattedValue(value?.toString(), format || 'none', precision);
diff --git a/frontend/src/container/GridTableComponent/index.tsx b/frontend/src/container/GridTableComponent/index.tsx
index 6e5d3e9d2b..ac7e2c9931 100644
--- a/frontend/src/container/GridTableComponent/index.tsx
+++ b/frontend/src/container/GridTableComponent/index.tsx
@@ -48,6 +48,7 @@ function GridTableComponent({
widgetId,
panelType,
queryRangeRequest,
+ decimalPrecision,
...props
}: GridTableComponentProps): JSX.Element {
const { t } = useTranslation(['valueGraph']);
@@ -87,10 +88,19 @@ function GridTableComponent({
const newValue = { ...val };
Object.keys(val).forEach((k) => {
const unit = getColumnUnit(k, columnUnits);
- if (unit) {
+ // Apply formatting if:
+ // 1. Column has a unit defined, OR
+ // 2. decimalPrecision is specified (format all values)
+ const shouldFormat = unit || decimalPrecision !== undefined;
+
+ if (shouldFormat) {
// the check below takes care of not adding units for rows that have n/a or null values
if (val[k] !== 'n/a' && val[k] !== null) {
- newValue[k] = getYAxisFormattedValue(String(val[k]), unit);
+ newValue[k] = getYAxisFormattedValue(
+ String(val[k]),
+ unit || 'none',
+ decimalPrecision,
+ );
} else if (val[k] === null) {
newValue[k] = 'n/a';
}
@@ -103,7 +113,7 @@ function GridTableComponent({
return mutateDataSource;
},
- [columnUnits],
+ [columnUnits, decimalPrecision],
);
const dataSource = useMemo(() => applyColumnUnits(originalDataSource), [
diff --git a/frontend/src/container/GridTableComponent/types.ts b/frontend/src/container/GridTableComponent/types.ts
index a1dac8104f..d3e55c9338 100644
--- a/frontend/src/container/GridTableComponent/types.ts
+++ b/frontend/src/container/GridTableComponent/types.ts
@@ -1,4 +1,5 @@
import { TableProps } from 'antd';
+import { PrecisionOption } from 'components/Graph/yAxisConfig';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { LogsExplorerTableProps } from 'container/LogsExplorerTable/LogsExplorerTable.interfaces';
import {
@@ -15,6 +16,7 @@ export type GridTableComponentProps = {
query: Query;
thresholds?: ThresholdProps[];
columnUnits?: ColumnUnit;
+ decimalPrecision?: PrecisionOption;
tableProcessedDataRef?: React.MutableRefObject<RowData[]>;
sticky?: TableProps<RowData>['sticky'];
searchTerm?: string;
diff --git a/frontend/src/container/GridValueComponent/index.tsx b/frontend/src/container/GridValueComponent/index.tsx
index bb1b6851f4..54f4fdd9d9 100644
--- a/frontend/src/container/GridValueComponent/index.tsx
+++ b/frontend/src/container/GridValueComponent/index.tsx
@@ -99,7 +99,11 @@ function GridValueComponent({
rawValue={value}
value={
yAxisUnit
- ? getYAxisFormattedValue(String(value), yAxisUnit)
+ ? getYAxisFormattedValue(
+ String(value),
+ yAxisUnit,
+ widget?.decimalPrecision,
+ )
: value.toString()
}
/>
diff --git a/frontend/src/container/NewWidget/RightContainer/RightContainer.styles.scss b/frontend/src/container/NewWidget/RightContainer/RightContainer.styles.scss
index 4a6d8c27e0..b1da70c6cb 100644
--- a/frontend/src/container/NewWidget/RightContainer/RightContainer.styles.scss
+++ b/frontend/src/container/NewWidget/RightContainer/RightContainer.styles.scss
@@ -158,7 +158,8 @@
}
}
- .log-scale {
+ .log-scale,
+ .decimal-precision-selector {
margin-top: 16px;
display: flex;
justify-content: space-between;
diff --git a/frontend/src/container/NewWidget/RightContainer/constants.ts b/frontend/src/container/NewWidget/RightContainer/constants.ts
index b123636438..7638858d1e 100644
--- a/frontend/src/container/NewWidget/RightContainer/constants.ts
+++ b/frontend/src/container/NewWidget/RightContainer/constants.ts
@@ -192,3 +192,17 @@ export const panelTypeVsContextLinks: {
[PANEL_TYPES.TRACE]: false,
[PANEL_TYPES.EMPTY_WIDGET]: false,
} as const;
+
+export const panelTypeVsDecimalPrecision: {
+ [key in PANEL_TYPES]: boolean;
+} = {
+ [PANEL_TYPES.TIME_SERIES]: true,
+ [PANEL_TYPES.VALUE]: true,
+ [PANEL_TYPES.TABLE]: true,
+ [PANEL_TYPES.LIST]: false,
+ [PANEL_TYPES.PIE]: true,
+ [PANEL_TYPES.BAR]: true,
+ [PANEL_TYPES.HISTOGRAM]: false,
+ [PANEL_TYPES.TRACE]: false,
+ [PANEL_TYPES.EMPTY_WIDGET]: false,
+} as const;
diff --git a/frontend/src/container/NewWidget/RightContainer/index.tsx b/frontend/src/container/NewWidget/RightContainer/index.tsx
index 8e1d3586f5..d472fcd912 100644
--- a/frontend/src/container/NewWidget/RightContainer/index.tsx
+++ b/frontend/src/container/NewWidget/RightContainer/index.tsx
@@ -12,6 +12,10 @@ import {
Switch,
Typography,
} from 'antd';
+import {
+ PrecisionOption,
+ PrecisionOptionsEnum,
+} from 'components/Graph/yAxisConfig';
import TimePreference from 'components/TimePreferenceDropDown';
import { PANEL_TYPES, PanelDisplay } from 'constants/queryBuilder';
import GraphTypes, {
@@ -48,6 +52,7 @@ import {
panelTypeVsColumnUnitPreferences,
panelTypeVsContextLinks,
panelTypeVsCreateAlert,
+ panelTypeVsDecimalPrecision,
panelTypeVsFillSpan,
panelTypeVsLegendColors,
panelTypeVsLegendPosition,
@@ -95,6 +100,8 @@ function RightContainer({
selectedTime,
yAxisUnit,
setYAxisUnit,
+ decimalPrecision,
+ setDecimalPrecision,
setGraphHandler,
thresholds,
combineHistogram,
@@ -160,6 +167,7 @@ function RightContainer({
panelTypeVsColumnUnitPreferences[selectedGraph];
const allowContextLinks =
panelTypeVsContextLinks[selectedGraph] && enableDrillDown;
+ const allowDecimalPrecision = panelTypeVsDecimalPrecision[selectedGraph];
const { currentQuery } = useQueryBuilder();
@@ -356,6 +364,30 @@ function RightContainer({
}
/>
)}
+
+ {allowDecimalPrecision && (
+ <section className="decimal-precision-selector">
+ <Typography.Text className="typography">
+ Decimal Precision
+ </Typography.Text>
+ <Select
+ options={[
+ { label: '0 decimals', value: PrecisionOptionsEnum.ZERO },
+ { label: '1 decimal', value: PrecisionOptionsEnum.ONE },
+ { label: '2 decimals', value: PrecisionOptionsEnum.TWO },
+ { label: '3 decimals', value: PrecisionOptionsEnum.THREE },
+ { label: '4 decimals', value: PrecisionOptionsEnum.FOUR },
+ { label: 'Full Precision', value: PrecisionOptionsEnum.FULL },
+ ]}
+ value={decimalPrecision}
+ style={{ width: '100%' }}
+ className="panel-type-select"
+ defaultValue={PrecisionOptionsEnum.TWO}
+ onChange={(val: PrecisionOption): void => setDecimalPrecision(val)}
+ />
+ </section>
+ )}
+
{allowSoftMinMax && (
<section className="soft-min-max">
<section className="container">
@@ -553,6 +585,8 @@ interface RightContainerProps {
setBucketWidth: Dispatch<SetStateAction<number>>;
setBucketCount: Dispatch<SetStateAction<number>>;
setYAxisUnit: Dispatch<SetStateAction<string>>;
+ decimalPrecision: PrecisionOption;
+ setDecimalPrecision: Dispatch<SetStateAction<PrecisionOption>>;
setGraphHandler: (type: PANEL_TYPES) => void;
thresholds: ThresholdProps[];
setThresholds: Dispatch<SetStateAction<ThresholdProps[]>>;
diff --git a/frontend/src/container/NewWidget/index.tsx b/frontend/src/container/NewWidget/index.tsx
index d00f97ec3c..67facc9bed 100644
--- a/frontend/src/container/NewWidget/index.tsx
+++ b/frontend/src/container/NewWidget/index.tsx
@@ -4,6 +4,10 @@ import './NewWidget.styles.scss';
import { WarningOutlined } from '@ant-design/icons';
import { Button, Flex, Modal, Space, Typography } from 'antd';
import logEvent from 'api/common/logEvent';
+import {
+ PrecisionOption,
+ PrecisionOptionsEnum,
+} from 'components/Graph/yAxisConfig';
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
import { adjustQueryForV5 } from 'components/QueryBuilderV2/utils';
import { QueryParams } from 'constants/query';
@@ -178,6 +182,10 @@ function NewWidget({
selectedWidget?.yAxisUnit || 'none',
);
+ const [decimalPrecision, setDecimalPrecision] = useState<PrecisionOption>(
+ selectedWidget?.decimalPrecision ?? PrecisionOptionsEnum.TWO,
+ );
+
const [stackedBarChart, setStackedBarChart] = useState<boolean>(
selectedWidget?.stackedBarChart || false,
);
@@ -257,6 +265,7 @@ function NewWidget({
opacity,
nullZeroValues: selectedNullZeroValue,
yAxisUnit,
+ decimalPrecision,
thresholds,
softMin,
softMax,
@@ -290,6 +299,7 @@ function NewWidget({
thresholds,
title,
yAxisUnit,
+ decimalPrecision,
bucketWidth,
bucketCount,
combineHistogram,
@@ -493,6 +503,8 @@ function NewWidget({
title: selectedWidget?.title,
stackedBarChart: selectedWidget?.stackedBarChart || false,
yAxisUnit: selectedWidget?.yAxisUnit,
+ decimalPrecision:
+ selectedWidget?.decimalPrecision || PrecisionOptionsEnum.TWO,
panelTypes: graphType,
query: adjustedQueryForV5,
thresholds: selectedWidget?.thresholds,
@@ -522,6 +534,8 @@ function NewWidget({
title: selectedWidget?.title,
stackedBarChart: selectedWidget?.stackedBarChart || false,
yAxisUnit: selectedWidget?.yAxisUnit,
+ decimalPrecision:
+ selectedWidget?.decimalPrecision || PrecisionOptionsEnum.TWO,
panelTypes: graphType,
query: adjustedQueryForV5,
thresholds: selectedWidget?.thresholds,
@@ -836,6 +850,8 @@ function NewWidget({
setSelectedTime={setSelectedTime}
selectedTime={selectedTime}
setYAxisUnit={setYAxisUnit}
+ decimalPrecision={decimalPrecision}
+ setDecimalPrecision={setDecimalPrecision}
thresholds={thresholds}
setThresholds={setThresholds}
selectedWidget={selectedWidget}
diff --git a/frontend/src/container/NewWidget/utils.ts b/frontend/src/container/NewWidget/utils.ts
index 10c08cf485..58cbb544df 100644
--- a/frontend/src/container/NewWidget/utils.ts
+++ b/frontend/src/container/NewWidget/utils.ts
@@ -1,5 +1,6 @@
import { DefaultOptionType } from 'antd/es/select';
import { omitIdFromQuery } from 'components/ExplorerCard/utils';
+import { PrecisionOptionsEnum } from 'components/Graph/yAxisConfig';
import {
initialQueryBuilderFormValuesMap,
PANEL_TYPES,
@@ -554,6 +555,7 @@ export const getDefaultWidgetData = (
softMax: null,
softMin: null,
stackedBarChart: name === PANEL_TYPES.BAR,
+ decimalPrecision: PrecisionOptionsEnum.TWO, // default decimal precision
selectedLogFields: defaultLogsSelectedColumns.map((field) => ({
...field,
type: field.fieldContext ?? '',
diff --git a/frontend/src/container/PanelWrapper/PiePanelWrapper.tsx b/frontend/src/container/PanelWrapper/PiePanelWrapper.tsx
index 1d297bfa17..5136da3741 100644
--- a/frontend/src/container/PanelWrapper/PiePanelWrapper.tsx
+++ b/frontend/src/container/PanelWrapper/PiePanelWrapper.tsx
@@ -104,6 +104,7 @@ function PiePanelWrapper({
const formattedTotal = getYAxisFormattedValue(
totalValue.toString(),
widget?.yAxisUnit || 'none',
+ widget?.decimalPrecision,
);
// Extract numeric part and unit separately for styling
@@ -219,6 +220,7 @@ function PiePanelWrapper({
const displayValue = getYAxisFormattedValue(
arc.data.value,
widget?.yAxisUnit || 'none',
+ widget?.decimalPrecision,
);
// Determine text anchor based on position in the circle
diff --git a/frontend/src/container/PanelWrapper/TablePanelWrapper.tsx b/frontend/src/container/PanelWrapper/TablePanelWrapper.tsx
index e791908629..4c50e4bbf7 100644
--- a/frontend/src/container/PanelWrapper/TablePanelWrapper.tsx
+++ b/frontend/src/container/PanelWrapper/TablePanelWrapper.tsx
@@ -40,6 +40,7 @@ function TablePanelWrapper({
enableDrillDown={enableDrillDown}
panelType={widget.panelTypes}
queryRangeRequest={queryRangeRequest}
+ decimalPrecision={widget.decimalPrecision}
// eslint-disable-next-line react/jsx-props-no-spreading
{...GRID_TABLE_CONFIG}
/>
diff --git a/frontend/src/container/PanelWrapper/UplotPanelWrapper.tsx b/frontend/src/container/PanelWrapper/UplotPanelWrapper.tsx
index d54cc1c9be..9ac58bb44b 100644
--- a/frontend/src/container/PanelWrapper/UplotPanelWrapper.tsx
+++ b/frontend/src/container/PanelWrapper/UplotPanelWrapper.tsx
@@ -249,6 +249,7 @@ function UplotPanelWrapper({
}) => {
legendScrollPositionRef.current = position;
},
+ decimalPrecision: widget.decimalPrecision,
}),
[
queryResponse.data?.payload,
diff --git a/frontend/src/container/PanelWrapper/__tests__/ValuePanelWrapper.test.tsx b/frontend/src/container/PanelWrapper/__tests__/ValuePanelWrapper.test.tsx
index 1d75cf54c6..362b31c4b9 100644
--- a/frontend/src/container/PanelWrapper/__tests__/ValuePanelWrapper.test.tsx
+++ b/frontend/src/container/PanelWrapper/__tests__/ValuePanelWrapper.test.tsx
@@ -27,7 +27,7 @@ describe('Value panel wrappper tests', () => {
);
// selected y axis unit as miliseconds (ms)
- expect(getByText('295')).toBeInTheDocument();
+ expect(getByText('295.43')).toBeInTheDocument();
expect(getByText('ms')).toBeInTheDocument();
});
diff --git a/frontend/src/container/PanelWrapper/__tests__/__snapshots__/TablePanelWrapper.test.tsx.snap b/frontend/src/container/PanelWrapper/__tests__/__snapshots__/TablePanelWrapper.test.tsx.snap
index a3f11cd65c..cf97f17906 100644
--- a/frontend/src/container/PanelWrapper/__tests__/__snapshots__/TablePanelWrapper.test.tsx.snap
+++ b/frontend/src/container/PanelWrapper/__tests__/__snapshots__/TablePanelWrapper.test.tsx.snap
@@ -330,7 +330,7 @@ exports[`Table panel wrappper tests table should render fine with the query resp
<div
class="line-clamped-wrapper__text"
>
- 431 ms
+ 431.25 ms
</div>
</div>
</div>
@@ -368,7 +368,7 @@ exports[`Table panel wrappper tests table should render fine with the query resp
<div
class="line-clamped-wrapper__text"
>
- 431 ms
+ 431.25 ms
</div>
</div>
</div>
@@ -406,7 +406,7 @@ exports[`Table panel wrappper tests table should render fine with the query resp
<div
class="line-clamped-wrapper__text"
>
- 287 ms
+ 287.11 ms
</div>
</div>
</div>
@@ -444,7 +444,7 @@ exports[`Table panel wrappper tests table should render fine with the query resp
<div
class="line-clamped-wrapper__text"
>
- 230 ms
+ 230.02 ms
</div>
</div>
</div>
@@ -482,7 +482,7 @@ exports[`Table panel wrappper tests table should render fine with the query resp
<div
class="line-clamped-wrapper__text"
>
- 66.4 ms
+ 66.37 ms
</div>
</div>
</div>
diff --git a/frontend/src/container/PanelWrapper/__tests__/__snapshots__/ValuePanelWrapper.test.tsx.snap b/frontend/src/container/PanelWrapper/__tests__/__snapshots__/ValuePanelWrapper.test.tsx.snap
index edde0ab5e1..3d5c930e08 100644
--- a/frontend/src/container/PanelWrapper/__tests__/__snapshots__/ValuePanelWrapper.test.tsx.snap
+++ b/frontend/src/container/PanelWrapper/__tests__/__snapshots__/ValuePanelWrapper.test.tsx.snap
@@ -51,7 +51,7 @@ exports[`Value panel wrappper tests should render tooltip when there are conflic
class="ant-typography value-graph-text css-dev-only-do-not-override-2i2tap"
style="color: Blue; font-size: 16px;"
>
- 295
+ 295.43
</span>
<span
class="ant-typography value-graph-unit css-dev-only-do-not-override-2i2tap"
diff --git a/frontend/src/lib/uPlotLib/getUplotChartOptions.ts b/frontend/src/lib/uPlotLib/getUplotChartOptions.ts
index fc90ad54d8..948cd88054 100644
--- a/frontend/src/lib/uPlotLib/getUplotChartOptions.ts
+++ b/frontend/src/lib/uPlotLib/getUplotChartOptions.ts
@@ -47,6 +47,7 @@ export interface GetUPlotChartOptions {
panelType?: PANEL_TYPES;
onDragSelect?: (startTime: number, endTime: number) => void;
yAxisUnit?: string;
+ decimalPrecision?: PrecisionOption;
onClickHandler?: OnClickPluginOpts['onClick'];
graphsVisibilityStates?: boolean[];
setGraphsVisibilityStates?: FullViewProps['setGraphsVisibilityStates'];
@@ -192,6 +193,7 @@ export const getUPlotChartOptions = ({
apiResponse,
onDragSelect,
yAxisUnit,
+ decimalPrecision,
minTimeScale,
maxTimeScale,
onClickHandler = _noop,
@@ -359,6 +361,7 @@ export const getUPlotChartOptions = ({
colorMapping,
customTooltipElement,
query: query || currentQuery,
+ decimalPrecision,
}),
onClickPlugin({
onClick: onClickHandler,
diff --git a/frontend/src/lib/uPlotLib/plugins/tooltipPlugin.ts b/frontend/src/lib/uPlotLib/plugins/tooltipPlugin.ts
index 731fbbd0d5..c648e00a03 100644
--- a/frontend/src/lib/uPlotLib/plugins/tooltipPlugin.ts
+++ b/frontend/src/lib/uPlotLib/plugins/tooltipPlugin.ts
@@ -1,4 +1,4 @@
-import { getToolTipValue } from 'components/Graph/yAxisConfig';
+import { getToolTipValue, PrecisionOption } from 'components/Graph/yAxisConfig';
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
import { themeColors } from 'constants/theme';
import dayjs from 'dayjs';
@@ -44,6 +44,7 @@ const generateTooltipContent = (
idx: number,
isDarkMode: boolean,
yAxisUnit?: string,
+ decimalPrecision?: PrecisionOption,
series?: uPlot.Options['series'],
isBillingUsageGraphs?: boolean,
isHistogramGraphs?: boolean,
@@ -127,7 +128,7 @@ const generateTooltipContent = (
let tooltipItemLabel = label;
if (Number.isFinite(value)) {
- const tooltipValue = getToolTipValue(value, yAxisUnit);
+ const tooltipValue = getToolTipValue(value, yAxisUnit, decimalPrecision);
const dataIngestedFormated = getToolTipValue(dataIngested);
if (
duplicatedLegendLabels[label] ||
@@ -239,6 +240,7 @@ type ToolTipPluginProps = {
isBillingUsageGraphs?: boolean;
isHistogramGraphs?: boolean;
isMergedSeries?: boolean;
+ decimalPrecision?: PrecisionOption;
stackBarChart?: boolean;
isDarkMode: boolean;
customTooltipElement?: HTMLDivElement;
@@ -259,6 +261,7 @@ const tooltipPlugin = ({
timezone,
colorMapping,
query,
+ decimalPrecision,
}: // eslint-disable-next-line sonarjs/cognitive-complexity
ToolTipPluginProps): any => {
let over: HTMLElement;
@@ -320,6 +323,7 @@ ToolTipPluginProps): any => {
idx,
isDarkMode,
yAxisUnit,
+ decimalPrecision,
u.series,
isBillingUsageGraphs,
isHistogramGraphs,
diff --git a/frontend/src/lib/uPlotLib/utils/getAxes.ts b/frontend/src/lib/uPlotLib/utils/getAxes.ts
index 4742ed22b2..6a2a65aa1c 100644
--- a/frontend/src/lib/uPlotLib/utils/getAxes.ts
+++ b/frontend/src/lib/uPlotLib/utils/getAxes.ts
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck
-import { getToolTipValue } from 'components/Graph/yAxisConfig';
+import { getToolTipValue, PrecisionOption } from 'components/Graph/yAxisConfig';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { uPlotXAxisValuesFormat } from './constants';
@@ -18,11 +18,13 @@ const getAxes = ({
yAxisUnit,
panelType,
isLogScale,
+ decimalPrecision,
}: {
isDarkMode: boolean;
yAxisUnit?: string;
panelType?: PANEL_TYPES;
isLogScale?: boolean;
+ decimalPrecision?: PrecisionOption;
// eslint-disable-next-line sonarjs/cognitive-complexity
}): any => [
{
@@ -61,7 +63,7 @@ const getAxes = ({
if (v === null || v === undefined || Number.isNaN(v)) {
return '';
}
- const value = getToolTipValue(v.toString(), yAxisUnit);
+ const value = getToolTipValue(v.toString(), yAxisUnit, decimalPrecision);
return `${value}`;
}),
gap: 5,
diff --git a/frontend/src/types/api/dashboard/getAll.ts b/frontend/src/types/api/dashboard/getAll.ts
index 3d8304e24a..c41d6ae57b 100644
--- a/frontend/src/types/api/dashboard/getAll.ts
+++ b/frontend/src/types/api/dashboard/getAll.ts
@@ -1,3 +1,4 @@
+import { PrecisionOption } from 'components/Graph/yAxisConfig';
import { PANEL_GROUP_TYPES, PANEL_TYPES } from 'constants/queryBuilder';
import { ThresholdProps } from 'container/NewWidget/RightContainer/Threshold/types';
import { timePreferenceType } from 'container/NewWidget/RightContainer/timeItems';
@@ -113,6 +114,7 @@ export interface IBaseWidget {
timePreferance: timePreferenceType;
stepSize?: number;
yAxisUnit?: string;
+ decimalPrecision?: PrecisionOption; // number of decimals or 'full precision'
stackedBarChart?: boolean;
bucketCount?: number;
bucketWidth?: number;