_.toSafeInteger(value)

171

_.toSafeInteger(value)

_.toSafeInteger将一个值转换成一个安全的整数。一个安全整数能够被正确的比较和表示

参数

value (*): 需要转换的值

返回值

(number): 返回转换好整数

例子

_.toSafeInteger(3.2);
// => 3
 
_.toSafeInteger(Number.MIN_VALUE);
// => 0
 
_.toSafeInteger(Infinity);
// => 9007199254740991
 
_.toSafeInteger('3.2');
// => 3

源代码

import toInteger from './toInteger.js'

/** Used as references for various `Number` constants. */
const MAX_SAFE_INTEGER = 9007199254740991

/**
 * Converts `value` to a safe integer. A safe integer can be compared and
 * represented correctly.
 *
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted integer.
 * @example
 *
 * toSafeInteger(3.2)
 * // => 3
 *
 * toSafeInteger(Number.MIN_VALUE)
 * // => 0
 *
 * toSafeInteger(Infinity)
 * // => 9007199254740991
 *
 * toSafeInteger('3.2')
 * // => 3
 */
//将一个值转换成一个安全的整数。一个安全整数能够被正确的比较和表示
function toSafeInteger(value) {
  if (!value) {//如果value是假,返回0
    return value === 0 ? value : 0
  }
  value = toInteger(value)//将value转换成整数
  if (value < -MAX_SAFE_INTEGER) {//如果value小于负的最大安全整数,返回负的最大安全整数
    return -MAX_SAFE_INTEGER
  }
  if (value > MAX_SAFE_INTEGER) {//如果value大于正的最大安全整数,返回正的最大安全整数
    return MAX_SAFE_INTEGER
  }
  return value
}

export default toSafeInteger

 

posted @ 2019-01-15 16:48  hahazexia  阅读(326)  评论(0)    收藏  举报