Number formatting: Strip trailing zeros after decimal point when decimals=auto (#57373)

This commit is contained in:
Leon Sorokin 2022-10-20 17:56:21 -05:00 committed by GitHub
parent 883d61d191
commit 7eac79b5f8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 3 deletions

View File

@ -305,7 +305,7 @@ describe('Format value', () => {
const value = 1200;
const instance = getDisplayProcessorFromConfig({ decimals: null, unit: 'short' });
const disp = instance(value);
expect(disp.text).toEqual('1.20');
expect(disp.text).toEqual('1.2');
expect(disp.suffix).toEqual(' K');
});
@ -329,10 +329,17 @@ describe('Format value', () => {
const value = 1500000;
const instance = getDisplayProcessorFromConfig({ decimals: null, unit: 'short' });
const disp = instance(value);
expect(disp.text).toEqual('1.50');
expect(disp.text).toEqual('1.5');
expect(disp.suffix).toEqual(' Mil');
});
it('with value 15000000 and unit locale', () => {
const value = 1500000;
const instance = getDisplayProcessorFromConfig({ decimals: null, unit: 'locale' });
const disp = instance(value);
expect(disp.text).toEqual('1,500,000');
});
it('with value 128000000 and unit bytes', () => {
const value = 1280000125;
const instance = getDisplayProcessorFromConfig({ decimals: null, unit: 'bytes' });

View File

@ -72,6 +72,12 @@ export function getDisplayProcessor(options?: DisplayProcessorOptions): DisplayP
unit = 'string';
}
const hasBoolUnit = unit === 'bool';
const isNumType = field.type === FieldType.number;
const isLocaleFormat = unit === 'locale';
const shouldTrimTrailingDecimalZeros =
!hasDateUnit && !hasBoolUnit && !isLocaleFormat && isNumType && config.decimals == null;
const formatFunc = getValueFormat(unit || 'none');
const scaleFunc = getScaleCalculator(field, options.theme);
@ -109,9 +115,18 @@ export function getDisplayProcessor(options?: DisplayProcessorOptions): DisplayP
}
}
if (!isNaN(numeric)) {
if (!Number.isNaN(numeric)) {
if (text == null && !isBoolean(value)) {
const v = formatFunc(numeric, decimals ?? config.decimals, null, options.timeZone, showMs);
// if no explicit decimals config, we strip trailing zeros e.g. 60.00 -> 60
// this is needed because we may have determined the minimum required `decimals` for y tick increments based on
// e.g. 'seconds' field unit (0.15s, 0.20s, 0.25s), but then formatFunc decided to return milli or nanos (150, 200, 250)
// so we end up with excess precision: 150.00, 200.00, 250.00
if (shouldTrimTrailingDecimalZeros) {
v.text = +v.text + '';
}
text = v.text;
suffix = v.suffix;
prefix = v.prefix;