前段时间测试提了一个bug,我打开一开,好家伙!原来是echarts饼状图数据展示百分比有一个与legend百分比的展示不一样。拿起手机一算果然,饼状图加在一起刚好100%,而legend加在一起是99.99%,0.01%的差距。查阅代码发现,之前同事做这部分legend的展示是通过数据四舍五入得到的,这就导致了0.01%的误差。自己有试验了几组数据,发现直接四舍五入跟饼状图展示的百分比确实会有很大差距,只能另找方法,试了几种都不好使,无奈去看了一下源码。找到了echarts百分比的算法。
echarts饼状图百分比是根据最大余额法来算的,源码请移步百分比算法,自己也根据源码进行了修改封装了一个方法,返回对应title百分比在legend展示即可
/**
* 饼状图百分比算法--最大余额法
* @param valueList 数值数组
* @param idx 索引下标
* @param precision 精确度
*/
export const getPercentWithPrecision = (
valueList: any[],
idx: any,
precision: number
): number => {
if (!valueList[idx]) {
return 0
}
const sum = valueList.reduce((acc, val) => {
return acc + (isNaN(val) ? 0 : val)
}, 0)
if (sum === 0) {
return 0
}
const digits = Math.pow(10, precision)
const votesPerQuota = valueList.map(val => {
return ((isNaN(val) ? 0 : val) / sum) * digits * 100
})
const targetSeats = digits * 100
const seats = votesPerQuota.map(votes => {
// Assign automatic seats.
return Math.floor(votes)
})
let currentSum = seats.reduce((acc, val) => {
return acc + val
}, 0)
const remainder = votesPerQuota.map((votes, idx) => {
return votes - seats[idx]
})
// Has remainding votes.
while (currentSum < targetSeats) {
// Find next largest remainder.
let max = Number.NEGATIVE_INFINITY
let maxId = null
for (let i = 0, len = remainder.length; i < len; ++i) {
if (remainder[i] > max) {
max = remainder[i]
maxId = i
}
}
// Add a vote to max remainder.
++seats[maxId]
remainder[maxId] = 0
++currentSum
}
return seats[idx] / digits
}