diff --git a/src/utils/src/data-utils.ts b/src/utils/src/data-utils.ts index 1b766b87b7..3fa94dd47e 100644 --- a/src/utils/src/data-utils.ts +++ b/src/utils/src/data-utils.ts @@ -163,6 +163,14 @@ export function preciseRound(num: number, decimals: number): string { ).toFixed(decimals); } +/** + * round a giving number at most 4 decimal places + * e.g. 10 -> 10, 1.12345 -> 1.2345, 2.0 -> 2 + */ +export function roundToFour(num: number): number { + // @ts-expect-error + return Number(`${Math.round(`${num}e+4`)}e-4`); +} /** * get number of decimals to round to for slider from step * @param step @@ -258,6 +266,8 @@ export function roundValToStep(minValue: number, step: number, val: number): num */ export const defaultFormatter: FieldFormatter = v => (notNullorUndefined(v) ? String(v) : ''); +export const floatFormatter = v => (isNumber(v) ? String(roundToFour(v)) : ''); + export const FIELD_DISPLAY_FORMAT: { [key: string]: FieldFormatter; } = { diff --git a/src/utils/src/index.ts b/src/utils/src/index.ts index 41a3cbbb52..d6e15e932d 100644 --- a/src/utils/src/index.ts +++ b/src/utils/src/index.ts @@ -61,6 +61,7 @@ export { arrayMove, getFormatter, applyDefaultFormat, + roundToFour, getBooleanFormatter, applyCustomFormat, datetimeFormatter, diff --git a/test/node/utils/data-utils-test.js b/test/node/utils/data-utils-test.js index 05f5807c13..ffaca5d39c 100644 --- a/test/node/utils/data-utils-test.js +++ b/test/node/utils/data-utils-test.js @@ -30,7 +30,8 @@ import { arrayMove, getFormatter, defaultFormatter, - formatNumber + formatNumber, + roundToFour } from '@kepler.gl/utils'; import {ALL_FIELD_TYPES} from '@kepler.gl/constants'; @@ -52,6 +53,19 @@ test('dataUtils -> preciseRound', t => { t.end(); }); +test('dataUtils -> roundToFour', t => { + t.equal(roundToFour(1.2344), 1.2344, 'should round 1.2344 to 4 decimals correctly'); + t.equal(roundToFour(13.23445), 13.2345, 'should round 13.23445 to 4 decimals correctly'); + t.equal(roundToFour(13), 13, 'should round 13 to 4 decimals correctly'); + t.equal(roundToFour(1.437), 1.437, 'should round 1.437 to 4 decimals correctly'); + t.equal( + roundToFour(0.09999999999999987), + 0.1, + 'should round 0.09999999999999987 to 4 decimals correctly' + ); + t.end(); +}); + test('dataUtils -> getRoundingDecimalFromStep', t => { t.equal(getRoundingDecimalFromStep(1), 0, 'decimal of step=int should be 0'); t.equal(getRoundingDecimalFromStep(0.1), 1, 'decimal of step=0.1 should be 1');