jquery 显示一位数百分比,跳过固定数字值

qxsslcnc  于 2023-02-21  发布在  jQuery
关注(0)|答案(2)|浏览(100)

我有一个函数将每个百分比四舍五入到1:

items() {
  return this.data
    .map(item => {
      const perc= item.count/ number * 100
      const percentage = parseFloat(perc).toFixed(1) + '%'

      return { ...item, percentage }
    })
    .sort((a, b) => b.count - a.count)
}

但问题是它也会对固定的数字进行四舍五入。例如:

100% => 100.0% -> issue

我该怎么补救呢?

j2qf4p5b

j2qf4p5b1#

四舍五入之前,请检查它是否为整数:

const vals = [0,1,1.1,1.1234, 100.0, 100]
const toPercentage = (x) => ((x|0) === x ? String(x) : x.toFixed(1)) + '%'

console.log(vals.map(toPercentage))

试试这样的方法:

sortedItems () {
  return this.data
    .map(item => {
      const perc = item.count/ this.smsData.number * 100
      const percentage = ((perc|0) === perc ? String(perc) : perc.toFixed(1)) + '%'
      return { ...item, percentage }
    })
    .sort((a, b) => b.count - a.count)
}

(Note perc已经是一个数字,所以不需要parseFloat()

k5hmc34c

k5hmc34c2#

使用numeraljs可以轻松实现这一点

numeral(1).format('0.[0]%') // '100%'
numeral(0.1).format('0.[0]%') // '10%'
numeral(0.56).format('0.[0]%') // '56%'

代码如下所示

sortedItems () {
  return this.data
    .map(item => {
      const percentage = numeral(item.count/this.smsData.number).format('0.[0]%')
      return { ...item, percentage }
    })
    .sort((a, b) => b.count - a.count)
}

相关问题