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

174

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

_.ceil将数字按照指定精度向上取整

参数

number (number): 需要舍入的数字
[precision=0] (number): 指定舍入的精度,正整数或者负整数

返回值

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

例子

_.ceil(4.006);
// => 5
 
_.ceil(6.004, 2);
// => 6.01
 
_.ceil(6040, -2);
// => 6100

源代码

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

/**
 * Computes `number` rounded up to `precision`.
 *
 * @since 3.10.0
 * @category Math
 * @param {number} number The number to round up.
 * @param {number} [precision=0] The precision to round up to.
 * @returns {number} Returns the rounded up number.
 * @example
 *
 * ceil(4.006)
 * // => 5
 *
 * ceil(6.004, 2)
 * // => 6.01
 *
 * ceil(6040, -2)
 * // => 6100
 */
//将数字按照指定精度向上取整
const ceil = createRound('ceil')

export default ceil
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取出最前面几位,截掉后面的位
      pair = `${value}e`.split('e')
      return +`${pair[0]}e${+pair[1] - precision}`
      //后面被截掉的位补零
    }
    return func(number)//用Math对象上原生方法处理number后返回结果
  }
}

export default createRound

 

posted @ 2019-04-16 09:08  hahazexia  阅读(332)  评论(0)    收藏  举报