toSafeInteger()
toSafeInteger(
value):number
Converts value to a safe integer.
DEPRECATED
Use manual conversion with Math.trunc() and clamping instead.
Parametersβ
value: unknownβ
The value to convert.
Returns: numberβ
The converted safe integer.
See Alsoβ
Sinceβ
2.0.0
Also known asβ
toSafeInteger (Lodash, es-toolkit) Β· β (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)
Exampleβ
// β Deprecated approach
toSafeInteger(3.7); // => 3
toSafeInteger(Infinity); // => 9007199254740991 (MAX_SAFE_INTEGER)
toSafeInteger(-Infinity); // => -9007199254740991 (MIN_SAFE_INTEGER)
// β
Recommended approach
Math.max(
Number.MIN_SAFE_INTEGER,
Math.min(Number.MAX_SAFE_INTEGER, Math.trunc(Number(value)))
);
How it works?β
Converts value to a safe integer.
Deprecated: Use Math.trunc() with bounds check.
Native Equivalentβ
// β toSafeInteger(value)
// β
Math.max(
// Number.MIN_SAFE_INTEGER,
// Math.min(Number.MAX_SAFE_INTEGER, Math.trunc(value))
// )
Use Casesβ
Convert to safe integer πβ
Convert to integer within safe range.
const safe = Math.max(
Number.MIN_SAFE_INTEGER,
Math.min(Number.MAX_SAFE_INTEGER, Math.trunc(Number(value)))
);
Clamp large numbersβ
Ensure number stays within safe precision.
function safeId(id: number): number {
const int = Math.trunc(id);
return Math.max(
Number.MIN_SAFE_INTEGER,
Math.min(Number.MAX_SAFE_INTEGER, int)
);
}