_.round(number, [precision=0])

184

_.round(number, [precision=0])
_.round计算一个数字四舍五入到某个精度的结果

参数

number (number): 需要四舍五入的数字
[precision=0] (number): 舍入到的精度

返回值

(number): 返回四舍五入后的结果

例子

_.round(4.006);
// => 4
 
_.round(4.006, 2);
// => 4.01
 
_.round(4060, -2);
// => 4100

源代码

import createRound from './.internal/createRound.js'

/**
 * Computes `number` rounded to `precision`.
 *
 * @since 3.10.0
 * @category Math
 * @param {number} number The number to round.
 * @param {number} [precision=0] The precision to round to.
 * @returns {number} Returns the rounded number.
 * @example
 *
 * round(4.006)
 * // => 4
 *
 * round(4.006, 2)
 * // => 4.01
 *
 * round(4060, -2)
 * // => 4100
 */
//计算一个数字四舍五入到某个精度的结果
const round = createRound('round')

export default round
createRound
/**
 * Creates a function like `round`.
 *
 * @private
 * @param {string} methodName The name of the `Math` method to use when rounding.
 * @returns {Function} Returns the new round function.
 */
//创建一个round方法用来对数字取整
function createRound(methodName) {
  const func = Math[methodName]//Math对象上对应的原生方法
  return (number, precision) => {
    precision = precision == null ? 0 : Math.min(precision, 292)//处理精度参数,精度最大取小数点后292位
    if (precision) {
      // Shift with exponential notation to avoid floating-point issues.
      // See [MDN](https://mdn.io/round#Examples) for more details.
      //指数表示法的转换,避免浮点问题
      let pair = `${number}e`.split('e')
      const value = func(`${pair[0]}e${+pair[1] + precision}`)
      //根据precision精度传递给Math.ceil或者Math.floor或者Math.round取出最前面几位,截掉后面的位
      pair = `${value}e`.split('e')
      return +`${pair[0]}e${+pair[1] - precision}`
      //后面被截掉的位补零
    }
    return func(number)//用Math对象上原生方法处理number后返回结果
  }
}

export default createRound

 

posted @ 2019-04-24 10:06  hahazexia  阅读(760)  评论(0)    收藏  举报