Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Display one digit percentage, skip fixed numbers vue

I have a function that rounds each percentage to 1:

sortedItems () {
  return this.data
    .map(item => {
      const perc= item.count/ this.smsData.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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading