Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

[Fix] round the float number to up to 4 decimal places in table (#2163)

Igor Dykhtaf640822aea6d
diff --git a/src/utils/src/data-utils.ts b/src/utils/src/data-utils.ts
index 1b766b87b..3fa94dd47 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 41a3cbbb5..d6e15e932 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 05f5807c1..ffaca5d39 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');