Skip to main content

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โ€‹

Number.MAX_SAFE_INTEGER - MDN


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