java How to Calculate Year on Year Growth Tool Class

  • 2021-10-16 01:54:32
  • OfStack

java calculation year-on-year growth tool class

For the rigor of the data, the system 1 is replaced by BigDecimal, without saying much, look at the code.


package com.pig4cloud.pigx.admin.api.util;
import java.math.BigDecimal;
public class PercentCount {
	public String percentBigDecimal(BigDecimal preNum,BigDecimal sufNum){
		double result = countDecimal(preNum,sufNum);
		if(result>0){
			return "+"+result+"%";
		}
		if(result<0){
			return result+"%";
		}
		if(result==0){
			return "+"+0+"%";
		}
		return null;
	}
	public  double countDecimal(BigDecimal preNum,BigDecimal sufNum){
		boolean preBoolean = verifyNum(preNum);
		boolean sufBoolean = verifyNum(sufNum);
		// At the same time true Calculation 
		if(preBoolean && sufBoolean){
			boolean b = verifyEqual(preNum, sufNum);
			if (b == false){
				return realCountDecimal(preNum,sufNum);
			}
			if (b){
				return 0;
			}
		}
		if(preBoolean == false && sufBoolean ==false){
			return 0;
		}
		if(sufBoolean ==false){
			return 100;
		}
		return  0;
	}
	// Verify that the number is zero sum null
	public boolean verifyNum(BigDecimal num){
		if(null !=num && num.compareTo(BigDecimal.ZERO)!=0 ){
			return true;
		}
		return false;
	}
	// Verify that two numbers are equal 
	public boolean verifyEqual(BigDecimal preNum,BigDecimal sufNum){
		int n = preNum.compareTo(sufNum);
		// Comparison  -1  Less than    0  Equal to     1  Greater than 
		if(n==0){
			return true;
		}
		return false;
	}
	// True calculation 
	public double realCountDecimal(BigDecimal preNum,BigDecimal sufNum){
		//( The preceding numbers - The numbers that follow )/ The numbers that follow *100
		BigDecimal bigDecimal = (preNum.subtract(sufNum)).divide(sufNum).multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_UP);
		if (bigDecimal.compareTo(BigDecimal.ZERO) !=0){
			return  bigDecimal.doubleValue();
		}
		return 0;
	}
	public static void main(String[] args) {
		PercentCount p = new PercentCount();
		BigDecimal a = new BigDecimal("3");
		BigDecimal b = new BigDecimal("1");
		String percent = p.percentBigDecimal(a, b);
		System.out.println(percent);
	}
}

Java calculation is year-on-year

Basic concepts and calculation formulas of year-on-year ring calculation

Year-on-year rate: the rate of increase or decrease of this year's data compared with the previous year's data

Calculation formula of year-on-year rate: rate = (data of this year-data of previous year)/data of previous year

Example: The number of tourists in October 2020 is 80W, the number of tourists in October 2019 is 100W, and the number of tourists in October 2018 is 90W

The year-on-year rate for 2020 is: rate: (80-100)/100 * 100% =-20%

The 2019 year-on-year rate is: rate: (100-900)/900 * 100% = +11%

("+" for increase, "-" for decrease)

Ring ratio: The rate at which this month's (quarterly) data increases or decreases compared with last month's (quarterly) data

Calculation formula of ring ratio: rate = (data of this month-data of last month)/data of last month

Example: The number of tourists in October 2020 is 100W, the number of tourists in September 2020 is 90W, and the number of tourists in July 2020 is 80W

The year-on-year rate in October 2020 is: rate: (100-90)/90 * 100% = +11%

The year-on-year rate in October 2019 is: rate: (90-80)/800 * 100% = +12.5%

Note: Year-on-year and month-on-month calculation formulas are the same, but the corresponding time of calculation data is different

Code implementation logic

Through time functions such as Calendar and HashMap, [hashmap (key, value) key is the time, value is the value corresponding to the time], the corresponding key and value11 are stored in the set, the corresponding value in HashMap is obtained by operating key, and then the corresponding value in HashMap is obtained by key, and the formula is calculated (the emphasis is on the operation of time (key), and value can be directly obtained by key for calculation)

Detailed logical steps

Firstly, the corresponding time and the corresponding data in the database are obtained by SQL statement, and sorted by time grouping


SELECT
        DATAS.DATE AS NAME ,
        SUM( DATAS.VISITORSUM) AS VALUE,
        2 AS sfzj,
        '' AS bfb
        FROM
        (SELECT TOURIST.* ,CONCAT(YEAR,' Year ',QUARTER,' Month ') AS DATE
        FROM TOURISTFLOW TOURIST)DATAS
        GROUP BY DATAS.DATE
        ORDER BY DATAS.DATE

Then set the time range, the earliest time minus 1 year is set as the minimum time, and the last time is the maximum time, which can guarantee the coverage of all data


//  Set the time range 
            //  Gets the first of the most recent times 1 List 
            analyzeBean firstTimeSubway = analyzeByYear.get(0);
            String startTime = firstTimeSubway.getTime();
            //  Gets the last of the last time 1 List 
            analyzeBean endTimeSubway = analyzeByYear.get(analyzeByYear.size() - 1);
            String endTime = endTimeSubway.getTime();
            //  Time format conversion 
            SimpleDateFormat format = new SimpleDateFormat("yyyy Year MM Month ");
            Date parse = format.parse(startTime);
            Date parse1 = format.parse(endTime);
            Calendar c = Calendar.getInstance();
            c.setTime(parse);
            c.add(Calendar.YEAR, -1);
            Date y = c.getTime();
            //  Gets the front of the most recent time 1 The time of year is used as the query range 
            String firstTime = format.format(y);
            analyzeRequestBean.setStartTime(firstTime);
            Calendar c1 = Calendar.getInstance();
            c1.setTime(parse1);
            Date y1 = c1.getTime();
            //  Get the last 1 The time of year is used as the query range 
            String lastTime = format.format(y1);
            analyzeRequestBean.setStartTime(lastTime);

When the result set of all data is stored in HashMap, hash (key, value) key is the time and value is the data value


hashMap.put(time, analyzeByYear.get(i).getValue());

Finally, time (key) is operated by for cycle, CaleCndar function and Date function, and then time (key) is calculated by finding the corresponding value in HashMap


for (int i = 0; i < analyzeByYear.size(); i++) {
                AnalyzeBean analyzeBean = analyzeByYear.get(i);
                if (i == 0) {
                	//  Whether to grow ( "0 : Decrease  1 : Increase  2 Neither increase nor decrease " ) 
                    analyzeBean.setSfzj(2);
                    analyzeBean.setBfb(null);
                } else {
                    SimpleDateFormat format2 = new SimpleDateFormat("yyyy Year MM Month ");
                    //  Current data 
                    Date parse2 = format2.parse(analyzeBean.getTime());
                    Calendar c2 = Calendar.gaetInstance();
                    c2.setTime(parse2);
                    c2.add(Calendar.YEAR, 0);
                    Date t = c2.getTime();
                    String time = format2.format(t);
                    Integer value = hashMap.get(time);
                    //  Data of previous years 
                    Date parse3 = format2.parse(time);
                    Calendar c3 = Calendar.getInstance();
                    c3.setTime(parse3);
                    c3.add(Calendar.YEAR, -1);
                    Date year = c3.getTime();
                    String time1 = format2.format(year);
                    Integer value1 = hashMap.get(time1);
                    if (null != value1 && null != value) {
                        if (value.equals(value1)) {
                            analyzeBean.setSfzj(2);
                            analyzeBean.setBfb(null);
                        } else {
                            if (value > value1) {
                                analyzeBean.setSfzj(1);
                            } else {
                                analyzeBean.setSfzj(0);
                            }
                            // 2 Individual value subtraction   Absolute value 
                            int abs = Math.abs(value - value1);
                            float a = (float) (abs) / (float) value1 * 100;
                            analyzeBean.setBfb(a + "");
                        }
                    } else {
                        analyzeBean.setSfzj(2);
                        analyzeBean.setBfb(null);
                    }
                }
            }

Year-on-year instance code:


 //  Seek year-on-year 
    @Override
    public Result getAnalyzeByYear(AnalyzeRequestBean analyzeRequestBean) {
        try {
            //  Check parameters 
            if (null == analyzeRequestBean) {
                return ResultUtil.fail(ResultEnum.PARAMS_ERROR);
            }
a
            List<AnalyzeBean> analyzeByYear
                    = InfoMapper.getAnalyzeByYear(analyzeRequestBean);
            if (analyzeByYear == null || analyzeByYear.size() == 0) {
                return ResultUtil.ok(null);
            }
            //  Set the time range 
            //  Gets the first of the most recent times 1 List 
            analyzeBean firstTimeSubway = analyzeByYear.get(0);
            String startTime = firstTimeSubway.getTime();
            //  Gets the last of the last time 1 List 
            analyzeBean endTimeSubway = analyzeByYear.get(analyzeByYear.size() - 1);
            String endTime = endTimeSubway.getTime();
            //  Time format conversion 
            SimpleDateFormat format = new SimpleDateFormat("yyyy Year MM Month ");
            Date parse = format.parse(startTime);
            Date parse1 = format.parse(endTime);
            Calendar c = Calendar.getInstance();
            c.setTime(parse);
            c.add(CaleCndar.YEAR, -1);
            Date y = c.getTime();
            //  Gets the front of the most recent time 1 The time of year is used as the query range 
            String firstTime = format.format(y);
            analyzeRequestBean.setStartTime(firstTime);
            Calendar c1 = Calendar.getInstance();
            c1.setTime(parse1);
            Date y1 = c1.getTime();
            //  Get the last 1 The time of year is used as the query range 
            String lastTime = format.format(y1);
            analyzeRequestBean.setStartTime(lastTime);
            //  Put a wide range of result sets into hashMap Medium 
            HashMap<String, Integer> hashMap = new HashMap<>();
            for (int i = 0; i < analyzeByYear.size(); i++) {
                analyzeBean analyzeBean = analyzeByYear.get(i);
                SimpleDateFormat format1 = new SimpleDateFormat("yyyy Year MM Month ");
                Date parse2 = format1.parse(analyzeBean.getTime());
                Calendar c2 = Calendar.getInstance();
                c2.setTime(parse2);
                c2.add(Calendar.YEAR, 0);
                Date t = c2.getTime();
                String time = format1.format(t);
                hashMap.put(time, analyzeByYear.get(i).getValue());
            }
            for (int i = 0; i < analyzeByYear.size(); i++) {
                AnalyzeBean analyzeBean = analyzeByYear.get(i);
                if (i == 0) {
                	//  Whether to grow ( "0 : Decrease  1 : Increase  2 Neither increase nor decrease " ) 
                    analyzeBean.setSfzj(2);
                    analyzeBean.setBfb(null);
                } else {
                    SimpleDateFormat format2 = new SimpleDateFormat("yyyy Year MM Month ");
                    //  Current data 
                    Date parse2 = format2.parse(analyzeBean.getTime());
                    Calendar c2 = Calendar.gaetInstance();
                    c2.setTime(parse2);
                    c2.add(Calendar.YEAR, 0);
                    Date t = c2.getTime();
                    String time = format2.format(t);
                    Integer value = hashMap.get(time);
                    //  Data of previous years 
                    Date parse3 = format2.parse(time);
                    Calendar c3 = Calendar.getInstance();
                    c3.setTime(parse3);
                    c3.add(Calendar.YEAR, -1);
                    Date year = c3.getTime();
                    String time1 = format2.format(year);
                    Integer value1 = hashMap.get(time1);
                    if (null != value1 && null != value) {
                        if (value.equals(value1)) {
                            analyzeBean.setSfzj(2);
                            analyzeBean.setBfb(null);
                        } else {
                            if (value > value1) {
                                analyzeBean.setSfzj(1);
                            } else {
                                analyzeBean.setSfzj(0);
                            }
                            // 2 Individual value subtraction   Absolute value 
                            int abs = Math.abs(value - value1);
                            float a = (float) (abs) / (float) value1 * 100;
                            analyzeBean.setBfb(a + "");
                        }
                    } else {
                        analyzeBean.setSfzj(2);
                        analyzeBean.setBfb(null);
                    }
                }
            }
            return ResultUtil.ok(analyzeByYear);
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        return ResultUtil.ok(null);
    }

The ring comparison is similar, except that c. add (Calendar. YEAR, 0); Replace with c. add (Calendar. MONTH, 0)

It is not difficult to realize logic, but it is complicated for me to write. If there is a better way, welcome to leave a message for exchange and discussion


Related articles: