Value to safe integer

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

More like this

  • Integer to roman numeral

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

    JavaScript, Math · Oct 22, 2020

  • Max array value based on function

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

    JavaScript, Math · Oct 21, 2020

  • Min array value based on function

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

    JavaScript, Math · Oct 21, 2020