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)
);
}