Aller au contenu principal

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