JavaScript Convert a Value to Safe Integer
A safe integer is an integer that:
- Can be exactly represented as an IEEE-754 double precision number, and
- Whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation
Math.max()
andMath.min()
to find the closest safe value.Math.round()
to convert to an integer.
const toSafeInteger = num =>
Math.round(
Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)
);
Examples:
let result1 = toSafeInteger('3.1');
let result2 = toSafeInteger('5.5');
console.log(result1); // 3
console.log(result2); // 6
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.