Skip to content

Commit

Permalink
[Fix] round the float number to up to 4 decimal places in table (#2163)
Browse files Browse the repository at this point in the history
  • Loading branch information
igorDykhta committed Mar 25, 2023
1 parent a41e011 commit f640822
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/utils/src/data-utils.ts
Expand Up @@ -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
Expand Down Expand Up @@ -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;
} = {
Expand Down
1 change: 1 addition & 0 deletions src/utils/src/index.ts
Expand Up @@ -61,6 +61,7 @@ export {
arrayMove,
getFormatter,
applyDefaultFormat,
roundToFour,
getBooleanFormatter,
applyCustomFormat,
datetimeFormatter,
Expand Down
16 changes: 15 additions & 1 deletion test/node/utils/data-utils-test.js
Expand Up @@ -30,7 +30,8 @@ import {
arrayMove,
getFormatter,
defaultFormatter,
formatNumber
formatNumber,
roundToFour
} from '@kepler.gl/utils';
import {ALL_FIELD_TYPES} from '@kepler.gl/constants';

Expand All @@ -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');
Expand Down

0 comments on commit f640822

Please sign in to comment.