@base-ui-components/react
Version:
Base UI is a library of headless ('unstyled') React components and low-level hooks. You gain complete control over your app's CSS and accessibility features.
30 lines (29 loc) • 985 B
JavaScript
import { getFormatter } from '../../utils/formatNumber.js';
import { clamp } from '../../utils/clamp.js';
export function removeFloatingPointErrors(value, format = {}) {
return parseFloat(getFormatter('en-US', {
maximumFractionDigits: format.maximumFractionDigits,
minimumFractionDigits: format.minimumFractionDigits,
useGrouping: false
}).format(value));
}
export function toValidatedNumber(value, {
step,
minWithDefault,
maxWithDefault,
minWithZeroDefault,
format
}) {
if (value === null) {
return value;
}
const clampedValue = clamp(value, minWithDefault, maxWithDefault);
// Ensure values are divisible by the step, starting from the min value.
if (step != null) {
const stepsFromMin = (clampedValue - minWithZeroDefault) / step;
const roundedSteps = Math.round(stepsFromMin);
const snappedValue = minWithZeroDefault + roundedSteps * step;
return removeFloatingPointErrors(snappedValue, format);
}
return clampedValue;
}