Files
30-seconds-of-code/snippets/toSafeInteger.md
Isabelle Viktoria Maciohsek 8bf67754ce Make expertise a field
2022-03-01 20:21:45 +02:00

517 B

title, tags, expertise, firstSeen, lastUpdated
title tags expertise firstSeen lastUpdated
Value to safe integer math beginner 2018-01-08T17:12:46+02:00 2020-10-22T20:24:44+03:00

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