@trail-ui/shared-utils
Version:
A set of TrailUI utilities
37 lines (35 loc) • 895 B
JavaScript
// src/numbers.ts
function toNumber(value) {
const num = parseFloat(value);
return typeof num !== "number" || Number.isNaN(num) ? 0 : num;
}
function toPrecision(value, precision) {
let nextValue = toNumber(value);
const scaleFactor = 10 ** (precision != null ? precision : 10);
nextValue = Math.round(nextValue * scaleFactor) / scaleFactor;
return precision ? nextValue.toFixed(precision) : nextValue.toString();
}
function countDecimalPlaces(value) {
if (!Number.isFinite(value))
return 0;
let e = 1;
let p = 0;
while (Math.round(value * e) / e !== value) {
e *= 10;
p += 1;
}
return p;
}
function clampValue(value, min, max) {
if (value == null)
return value;
if (max < min) {
console.warn("clamp: max cannot be less than min");
}
return Math.min(Math.max(value, min), max);
}
export {
toPrecision,
countDecimalPlaces,
clampValue
};