toSafeInteger

JavaScript, Math

Converts a value to a safe integer.

  • Use Math.max() and Math.min() to find the closest safe value.
  • Use 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)
  );
toSafeInteger('3.2'); // 3
toSafeInteger(Infinity); // 9007199254740991

Recommended snippets

  • toRomanNumeral

    JavaScript, Math

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

  • arithmeticProgression

    JavaScript, Math

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

  • averageBy

    JavaScript, Math

    Calculates the average of an array, after mapping each element to a value using the provided function.