From f7b19bd97f6236d009bfda5a398939ea88c71522 Mon Sep 17 00:00:00 2001 From: Ilia Mashkov Date: Wed, 7 Jan 2026 16:48:49 +0300 Subject: [PATCH] feat: move functions to separate files --- .../lib/utils/clampNumber/clampNumber.ts | 10 ++++++++ .../getDecimalPlaces/getDecimalPlaces.ts | 17 +++++++++++++ .../roundToStepPrecision.ts | 24 +++++++++++++++++++ 3 files changed, 51 insertions(+) create mode 100644 src/shared/lib/utils/clampNumber/clampNumber.ts create mode 100644 src/shared/lib/utils/getDecimalPlaces/getDecimalPlaces.ts create mode 100644 src/shared/lib/utils/roundToStepPrecision/roundToStepPrecision.ts diff --git a/src/shared/lib/utils/clampNumber/clampNumber.ts b/src/shared/lib/utils/clampNumber/clampNumber.ts new file mode 100644 index 0000000..d3e28e4 --- /dev/null +++ b/src/shared/lib/utils/clampNumber/clampNumber.ts @@ -0,0 +1,10 @@ +/** + * Clamp a number within a range. + * @param value The number to clamp. + * @param min minimum value + * @param max maximum value + * @returns The clamped number. + */ +export function clampNumber(value: number, min: number, max: number): number { + return Math.min(Math.max(value, min), max); +} diff --git a/src/shared/lib/utils/getDecimalPlaces/getDecimalPlaces.ts b/src/shared/lib/utils/getDecimalPlaces/getDecimalPlaces.ts new file mode 100644 index 0000000..00451ac --- /dev/null +++ b/src/shared/lib/utils/getDecimalPlaces/getDecimalPlaces.ts @@ -0,0 +1,17 @@ +/** + * Get the number of decimal places in a number + * + * For example: + * - 1 -> 0 + * - 0.1 -> 1 + * - 0.01 -> 2 + * - 0.05 -> 2 + * + * @param step - The step number to analyze + * @returns The number of decimal places + */ +export function getDecimalPlaces(step: number): number { + const str = step.toString(); + const decimalPart = str.split('.')[1]; + return decimalPart ? decimalPart.length : 0; +} diff --git a/src/shared/lib/utils/roundToStepPrecision/roundToStepPrecision.ts b/src/shared/lib/utils/roundToStepPrecision/roundToStepPrecision.ts new file mode 100644 index 0000000..5ea6a24 --- /dev/null +++ b/src/shared/lib/utils/roundToStepPrecision/roundToStepPrecision.ts @@ -0,0 +1,24 @@ +import { getDecimalPlaces } from '$shared/lib/utils'; + +/** + * Round a value to the precision of the given step + * + * This fixes floating-point precision errors that occur with decimal steps. + * For example, with step=0.05, adding it repeatedly can produce values like + * 1.3499999999999999 instead of 1.35. + * + * We use toFixed() to round to the appropriate decimal places instead of + * Math.round(value / step) * step, which doesn't always work correctly + * due to floating-point arithmetic errors. + * + * @param value - The value to round + * @param step - The step to round to (defaults to 1) + * @returns The rounded value + */ +export function roundToStepPrecision(value: number, step: number = 1): number { + if (step <= 0) { + return value; + } + const decimals = getDecimalPlaces(step); + return parseFloat(value.toFixed(decimals)); +}