安全整数

时间:2022-07-23
本文章向大家介绍安全整数,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

value转化为一个安全整数

使用 Math.max()Math.min() 找到最接近的安全value

使用 Math.round() 将其转化为整数

const toSafeInteger = num =>
  Math.round(
    Math.max(
      Math.min(
        num, 
        Number.MAX_SAFE_INTEGER
      ), 
      Number.MIN_SAFE_INTEGER
    )
  );

例子:

// 3
toSafeInteger('3.2'); 
// 9007199254740991
toSafeInteger(Infinity);