Javascript toFixed function

前端 未结 6 1701
春和景丽
春和景丽 2020-12-30 04:51

The expected result of:

(1.175).toFixed(2) = 1.18 and
(5.175).toFixed(2) = 5.18

But in JS showing:

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-30 05:24

    obj = {
        round(val) {
          const delta = 0.00001
          let num = val
          if (num - Math.floor(num) === 0.5) {
            num += delta
          }
          return Math.round(num + delta)
        },
      fixed(val, count = 0) {
          const power = Math.pow(10, count)
          let res = this.round(val * power) / power
          let arr = `${res}`.split('.')
          let addZero = ''
          for (let i = 0; i < count; i++) {
            addZero += '0'
          }
          if (count > 0) {
            arr[1] = ((arr[1] || '') + addZero).substr(0, count)
          }
          return arr.join('.')
      }
    }
    obj.fixed(5.175, 2)
    

    // "5.18"

提交回复
热议问题