31 lines
991 B
TypeScript
31 lines
991 B
TypeScript
import { getDecimalPlaces } from '$shared/lib/utils';
|
|
|
|
/**
|
|
* Rounds a value to match the precision of a given step
|
|
*
|
|
* Fixes floating-point precision errors that occur with decimal arithmetic.
|
|
* For example, repeatedly adding 0.05 can produce 1.3499999999999999
|
|
* instead of 1.35 due to IEEE 754 floating-point representation.
|
|
*
|
|
* Uses toFixed() instead of Math.round() for correct decimal rounding.
|
|
*
|
|
* @param value - The value to round
|
|
* @param step - The step size to match precision of (default: 1)
|
|
* @returns The rounded value
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* roundToStepPrecision(1.3499999999999999, 0.05); // 1.35
|
|
* roundToStepPrecision(1.2345, 0.01); // 1.23
|
|
* roundToStepPrecision(1.2345, 0.1); // 1.2
|
|
* roundToStepPrecision(1.5, 1); // 2
|
|
* ```
|
|
*/
|
|
export function roundToStepPrecision(value: number, step: number = 1): number {
|
|
if (step <= 0) {
|
|
return value;
|
|
}
|
|
const decimals = getDecimalPlaces(step);
|
|
return parseFloat(value.toFixed(decimals));
|
|
}
|