echarts 圆环图 legend图例显示数值和百分比

知识点:Math.round()与toFixed()有所不同。虽然都是四舍五入,但是前者只能取整数,返回的是数字,后者可自定义小数位数,返回的是字符串(string)类型。
echarts 圆环图 legend图例显示数值和百分比_第1张图片

 let p = Math.round(((faultVal / total) * 100))//计算百分比

echarts 圆环图 legend图例显示数值和百分比_第2张图片
函数回调:

 formatter:function (name){
                let data = option.series[0].data;
                console.log(data);
                let total =0;
                let faultVal;
                for (let i = 0;i < data.length; i++){
                    total += data[i].value;//总数
                    if(data[i].name == name){
                        faultVal = data[i].value;
                    }
                    let v = faultVal;
                    //let p = Math.round(((faultVal / total) * 100))//计算百分比
                    let p = Math.round(((faultVal / total) * 100)).toFixed(2);
                    console.log(faultVal)
                    return `${name} ${v} ${p}%`
                }
            }

完整代码:

legend: {
            top:'12%',
            right: '3.5%',
            orient : 'vertical',
            icon: "rect",
            itemHeight: 12,
            itemGap:1,
            textStyle: { //图例⽂字的样式
                color: '#BACEE3',
                fontSize: 14
            },
            formatter:function (name){
                let data = option.series[0].data;
                console.log(data);
                let total =0;
                let faultVal;
                for (let i = 0;i < data.length; i++){
                    total += data[i].value;
                    if(data[i].name == name){
                        faultVal = data[i].value;
                    }
                    let v = faultVal;
                    let p = Math.round(((faultVal / total) * 100))
                    console.log(faultVal)
                    return `${name}  ${p}%`
                }
            }

你可能感兴趣的:(echarts,javascript,ecmascript)