Value to safe integer

OSCC · JavaScript, Math · Oct 22, 2020

Converts a value to a safe integer.

const toSafeInteger = num =>
  Math.round(
    Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)
  );
toSafeInteger('3.2'); // 3
toSafeInteger(Infinity); // 9007199254740991

Recommended snippets

  • Integer to roman numeral

    JavaScript, Math

    Converts an integer to its roman numeral representation. Accepts value between 1 and 3999 (both inclusive).

  • Arithmetic progression

    JavaScript, Math

    Creates an array of numbers in the arithmetic progression, starting with the given positive integer and up to the specified limit.

  • Digitize number

    JavaScript, Math

    Converts a number to an array of digits, removing its sign if necessary.