- Use
Math.max()
andMath.min()
to find the closest safe value. - Use
Math.round()
to convert to an integer.
Source
https://www.30secondsofcode.org/js/s/to-safe-integer
const toSafeInteger = num =>
Math.round(
Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)
);
// Examples
toSafeInteger('3.2'); // 3
toSafeInteger(Infinity); // 9007199254740991