Java求百分比(解决关于100%的问题)


@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;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值