计算增长率

/**
     * 计算增长率
     * @param currVal 当元素前值
     * @param preVal  上一个元素值
     * @return Map<String, String>
     */
    private Map<String, String> dealGrowthRate(Number currVal, Number preVal) {
        // 区分正负增长
        String preStr = "+";
        // 页面颜色标识
        String color = "green";
        // 增长率字符
        String growthRateStr = "";
        // 类型转换
        BigDecimal currValue = new BigDecimal("0.00");
        BigDecimal preValue = new BigDecimal("0.00");

        if (currVal instanceof Long && preVal instanceof Long) {
            // 类型转换
            currValue = BigDecimal.valueOf((Long) currVal);
            preValue = BigDecimal.valueOf((Long) preVal);
        } else if (currVal instanceof BigDecimal && preVal instanceof BigDecimal) {
            // 类型转换
            currValue = (BigDecimal) currVal;
            preValue = (BigDecimal) preVal;
        }

        // 增长率
        BigDecimal growthRate;
        if (0 == preValue.compareTo(BigDecimal.ZERO)) {
            if (0 == currValue.compareTo(BigDecimal.ZERO)) {
                preStr = "";
            }
            growthRateStr = preStr;
        } else {
            // 计算增长率
            growthRate = currValue.subtract(preValue).divide(preValue, 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100"));
            if (0 == growthRate.compareTo(BigDecimal.ZERO)) {
                preStr = "";
            } else if (0 > growthRate.compareTo(BigDecimal.ZERO)) {
                growthRate = growthRate.negate();
                preStr = "-";
                color = "red";
            }

            String bigDecimalStr = "";
            // 增长率
            BigDecimal bigDecimal = growthRate.setScale(2, BigDecimal.ROUND_HALF_UP);
            if (bigDecimal != null) {
                bigDecimalStr = bigDecimal.toString();
                if (bigDecimalStr.contains(".00")) {
                    // 增长率为整数,去除小数点
                    bigDecimalStr = bigDecimalStr.substring(0, bigDecimalStr.indexOf("."));
                }
            }
            growthRateStr = preStr + bigDecimalStr + "%";
        }

        // 返回结果
        Map<String, String> growthRateMap = new HashMap<>();
        growthRateMap.put("color", color);
        growthRateMap.put("growthRateStr", growthRateStr);
        return growthRateMap;
    }

 

posted @ 2021-07-06 17:38  二次元的程序猿  阅读(190)  评论(0编辑  收藏  举报