huliguo
2025-05-06 03e22f45b1b06b68a3ba8b9390e9a5f1ddda752a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.DecimalFormat;
 
public class DatabaseConnectionTest {
    public static void main(String[] args) {
        /*String url = "jdbc:mysql://localhost:3306/canlian?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
        String username = "root";
        String password = "123456";
 
        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            System.out.println("数据库连接成功!");
        } catch (SQLException e) {
            System.out.println("数据库连接失败:" + e.getMessage());
        }*/
        String s = calcRate(5, 4);
        System.out.println(s);
    }
    public static String calcRate(Integer currentValue, Integer previousValue) {
        //去年的数据为0的情况
        if (previousValue == 0){
            return currentValue == 0 ? "同比持平" : "无同比数据";
        }
        // 计算变化率
        double changeRate = (currentValue - previousValue) * 100.0 / previousValue;
        // 格式化输出(保留两位小数,带正负号)
        DecimalFormat df = new DecimalFormat("0.00");
        String absoluteValue = df.format(Math.abs(changeRate));
        if (changeRate > 0) {
            return "同比增加" + absoluteValue + "%";
        } else if (changeRate < 0) {
            return "同比减少" + absoluteValue + "%";
        } else {
            return "同比持平";
        }
 
    }
}