为JavaScript添加 字符串样式中的fixed()有什么用

JavaScript012

为JavaScript添加 字符串样式中的fixed()有什么用,第1张

fixed 方法

把 HTML <TT>标记放置在 String 对象中的文本两端。

strVariable.fixed( )

必选项 strVariable 参数为任意的 String 对象或文字。

说明

下面的示例说明了 fixed 方法如何工作:

var strVariable = "This is a string object"

strVariable = strVariable.fixed( )

最后一条语句执行完后,strVariable 的值是:

<TT>This is a string object</TT>

可以把该元素的定位设置为fixed,该元素就会始终在那个位置,不过要注意IE6下不支持固定定位,兼容IE6可以通过JS实现,不过JS实现的是滑动效果,要想在IE6下也实现固定定位那样的效果没办法做到。

// 重写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

}