From 7aaec2c4ced19e8468991da10b35c501e5fe50b7 Mon Sep 17 00:00:00 2001 From: Cody O'Donnell Date: Thu, 4 Apr 2024 10:08:49 -0700 Subject: [PATCH] Fix slider step precision --- src/common/utils/stringUtils.ts | 8 ++++++++ src/features/collections/CollectionDetail.tsx | 14 ++++++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/common/utils/stringUtils.ts b/src/common/utils/stringUtils.ts index 3e3c9aa8..d0ce1d4a 100644 --- a/src/common/utils/stringUtils.ts +++ b/src/common/utils/stringUtils.ts @@ -69,3 +69,11 @@ export function uriEncodeTemplateTag( export function formatNumber(num: number) { return num.toLocaleString(); } + +/** + * Count the number of decimals in a given float or int + */ +export function countDecimals(num: number) { + if (num % 1 !== 0) return num.toString().split('.')[1].length; + return 0; +} diff --git a/src/features/collections/CollectionDetail.tsx b/src/features/collections/CollectionDetail.tsx index 6552e072..347bb513 100644 --- a/src/features/collections/CollectionDetail.tsx +++ b/src/features/collections/CollectionDetail.tsx @@ -4,7 +4,10 @@ import { usePageTitle } from '../layout/layoutSlice'; import styles from './Collections.module.scss'; import { useEffect, useMemo, useRef, useState } from 'react'; import { DataProduct } from './DataProduct'; -import { snakeCaseToHumanReadable } from '../../common/utils/stringUtils'; +import { + countDecimals, + snakeCaseToHumanReadable, +} from '../../common/utils/stringUtils'; import { MATCHER_LABELS, MatchModal } from './MatchModal'; import { ExportModal } from './ExportModal'; import { Button, Input } from '../../common/components'; @@ -808,6 +811,13 @@ const RangeFilterControls = ({ } }, [filter.value, filterMax, filterMin, setValue]); + // Find the greatest number of decimal places used between the + // filter's max and min and use 10^-numDecimals as the step + const getStep = (min: number, max: number) => { + const numDecimals = Math.max(countDecimals(min), countDecimals(max)); + return parseFloat(Math.pow(10, -1 * numDecimals).toFixed(numDecimals)); + }; + return ( @@ -849,7 +859,7 @@ const RangeFilterControls = ({ step={ filter.type === 'int' ? 1 - : (filter.max_value - filter.min_value) / 100 + : getStep(filter.max_value, filter.min_value) } marks={[filter.min_value, filter.max_value].map((v) => ({ value: v,