JavaScript Convert a Value to Safe Integer

A safe integer is an integer that:

  1. Can be exactly represented as an IEEE-754 double precision number, and
  2. Whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation

Convert

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

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.