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