skip to Main Content

I have a function that rounds each percentage to 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)
}

But the problem is that it rounds also the fixed numbers. For example:

100% => 100.0% -> issue

So how can I fix this?

2

Answers


  1. Just check if it is a whole number before you round:

    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))

    Try something like this:

    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 that perc already is a number, so you don’t need parseFloat()

    Login or Signup to reply.
  2. You can easily achieve it with numeraljs

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

    So your code will look like this

    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)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search