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

176

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

_.floor对一个数字向下取整至某个精度

参数

number (number): 需要向下取整的数字
[precision=0] (number): 向下取整的精度

返回值

(number): 返回向下取整后的数字

例子

_.floor(4.006);
// => 4
 
_.floor(0.046, 2);
// => 0.04
 
_.floor(4060, -2);
// => 4000

源代码

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

/**
 * Computes `number` rounded down to `precision`.
 *
 * @since 3.10.0
 * @category Math
 * @param {number} number The number to round down.
 * @param {number} [precision=0] The precision to round down to.
 * @returns {number} Returns the rounded down number.
 * @example
 *
 * floor(4.006)
 * // => 4
 *
 * floor(0.046, 2)
 * // => 0.04
 *
 * floor(4060, -2)
 * // => 4000
 */
//对一个数字向下取整至某个精度
const floor = createRound('floor')

export default floor
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-21 15:34  hahazexia  阅读(420)  评论(0)    收藏  举报