@Data
public class BigScreenStatisticsVo {
@ApiModelProperty(value = "名称")
private String name;//
@ApiModelProperty(value = "数量")
private Integer amount;//
@ApiModelProperty(value = "占比")
@JsonSerialize(nullsUsing = NullSerializer.class)
private Double percentage;//占比
}
List<BigScreenStatisticsVo> drugAmountVos=hisPresDrugMapper.queryDrugAmount(preNums);
List<BigScreenStatisticsVo> drugpPrcentage = calculatePercentage(drugAmountVos, drugTotal, "percentage","amount");
/**
* @Author xqc
* @Description //求百分比 list数据,total总数,percentage百分比字段名,amount数量字段名
* @Date 2024/05/08 13:08
* @return
**/
public static <T> List<T> calculatePercentage(List<T> list,Integer total, String percentage,String amount) {
String[] result = new String[list.size()];
int i=0;
for (T t : list) {
try {
// 获取泛型对象 T 的 Class 对象
Class<?> clazz = t.getClass();
// 查找指定名称的属性
Field field1 = clazz.getDeclaredField(amount);//file
Field field = clazz.getDeclaredField(percentage);//fieldName
// 设置属性为可访问
field.setAccessible(true);
field1.setAccessible(true);
double ratio=( ((Integer)field1.get(t)*1.0)/total)*100;
// 创建DecimalFormat对象,指定保留一位小数(保留两位:0.00)
DecimalFormat decimalFormat = new DecimalFormat("0.00");
String Percentage = decimalFormat.format(ratio); // 格式化百分比
// 最后一位数据采用减法,这样总和为100%;
if(list.indexOf(t)==list.size()-1){
Double temp = 0.0;
for (int j = 0; j < result.length-1; j++) {
temp += Double.valueOf(result[j]);
}
double value = 100 - temp;
// 格式化百分比:解决double类型数字相加减的时候结果与预期不符合
String Percentage2 = decimalFormat.format(value);
result[i] = String.valueOf(Percentage2);
field.set(t,Double.valueOf(Percentage2));
}else {
// 设置属性的值
field.set(t, Double.valueOf(Percentage));
result[i] = String.valueOf(Percentage);
}
i++;
} catch (Exception e) {
log.error("计算百分比出错");
}
}
return list;
}