JS 重写toFixed方法

JavaScript07

JS 重写toFixed方法,第1张

// 重写toFixed方法

Number.prototype.toFixed = function (n) {

  if (n >20 || n <0) {

      throw new RangeError('toFixed() digits argument must be between 0 and 20')

  }

  const number = this

  if (isNaN(number) || number >= Math.pow(10, 21)) {

      return number.toString()

  }

  if (typeof (n) == 'undefined' || n == 0) {

      return (Math.round(number)).toString()

  }

  let result = number.toString()

  const arr = result.split('.')

  // 整数的情况

  if (arr.length <2) {

      result += '.'

      for (let i = 0i <ni += 1) {

          result += '0'

      }

      return result

  }

  const integer = arr[0]

  const decimal = arr[1]

  if (decimal.length == n) {

      return result

  }

  if (decimal.length <n) {

      for (let i = 0i <n - decimal.lengthi += 1) {

          result += '0'

      }

      return result

  }

  result = integer + '.' + decimal.substr(0, n)

  const last = decimal.substr(n, 1)

  // 四舍五入,转换为整数再处理,避免浮点数精度的损失  正数+1 负数-1

  if (parseInt(last, 10) >= 5) {

      const x = Math.pow(10, n)

      result = (Math.round((parseFloat(result) * x)) + (parseFloat(result) >0 ? 1 : -1)) / x

      result = result.toFixed(n)

  }

  return result

}

新建一个HTML文件,命名为test.html,用于实现把div定位到右上角。

在test.html页面编写一个内容为“这是固定在右上角的DIV”的div,并定义它的id属性为rig,用于下面实现定位。同时,编写几个p标签,用于测试div是否真的固定在页面的右上角。

在test.html页面,使用<style type="text/css"></style>标记定义CSS的内容,在CSS内编写id为rig的div样式。