计算工具类 (DataCalculatorUtil)
概述
DataCalculatorUtil 是一个专门为指标数据计算设计的工具类,支持多个实际值和运算符的灵活组合计算。该工具类特别适合处理复杂的计算场景,如系统中的综合评分、财务计算、统计分析等。
主要特性
1. 灵活的指标数据结构
- 支持多个实际值的组合计算
- 每个值可以指定对应的运算符
- 支持计算顺序控制
- 可添加描述信息便于理解
2. 多种计算方式
- 基础指标计算
- 字符串表达式计算
- 快速计算模式
- 有序计算支持
3. 丰富的配置选项
- 可自定义小数点位数
- 可配置舍入模式
- 支持严格模式验证
- 可控制是否允许负数或零值
4. 详细的计算结果
- 返回最终计算结果
- 提供中间计算步骤
- 记录计算耗时
- 完整的错误信息
核心组件
IndicatorDataItem 指标数据项
public static class IndicatorDataItem {
private BigDecimal value; // 实际值
private String operator; // 运算符(+、-、*、/、%)
private int order; // 计算顺序(可选)
private String description; // 描述信息
}
IndicatorCalculationConfig 计算配置
public static class IndicatorCalculationConfig {
private int scale = 2; // 保留小数位数
private RoundingMode roundingMode; // 舍入模式
private boolean allowNegative = true; // 是否允许负数
private boolean allowZero = true; // 是否允许零值
private boolean strictMode = false; // 严格模式
private String defaultOperator = "+"; // 默认运算符
private boolean autoOrder = true; // 是否自动排序
}
IndicatorCalculationResult 计算结果
public static class IndicatorCalculationResult {
private BigDecimal finalValue; // 最终计算结果
private List<BigDecimal> intermediateResults; // 中间计算结果
private List<String> calculationSteps; // 计算步骤说明
private boolean success; // 计算是否成功
private String errorMessage; // 错误信息
private long calculationTime; // 计算耗时
}
使用方法
1. 基础指标计算
import com.iflytek.enrollment.core.utils.IndicatorDataCalculatorUtil;
// 创建指标数据项:基础值100,加50,减20,乘1.5
List<IndicatorDataItem> dataItems = Arrays.asList(
new IndicatorDataItem(new BigDecimal("100"), null, "基础值"),
new IndicatorDataItem(new BigDecimal("50"), "+", "增加50"),
new IndicatorDataItem(new BigDecimal("20"), "-", "减少20"),
new IndicatorDataItem(new BigDecimal("1.5"), "*", "乘以1.5")
);
// 使用默认配置计算
BigDecimal result = IndicatorDataCalculatorUtil.calculateIndicator(dataItems);
// 结果:(100 + 50 - 20) * 1.5 = 195.00
2. 使用构建器模式
// 使用构建器创建指标数据项
List<IndicatorDataItem> dataItems = IndicatorDataCalculatorUtil.builder()
.addValue(new BigDecimal("1000"), "初始资金")
.addValue(new BigDecimal("200"), "+", "投资收益")
.addValue(new BigDecimal("50"), "-", "手续费")
.addValue(new BigDecimal("0.95"), "*", "税率调整")
.build();
BigDecimal result = IndicatorDataCalculatorUtil.calculateIndicator(dataItems);
// 结果:(1000 + 200 - 50) * 0.95 = 1092.50
3. 自定义配置计算
// 创建高精度配置
IndicatorCalculationConfig config = IndicatorDataCalculatorUtil.createHighPrecisionConfig();
config.setScale(4);
config.setRoundingMode(RoundingMode.HALF_DOWN);
List<IndicatorDataItem> dataItems = Arrays.asList(
new IndicatorDataItem(new BigDecimal("10.123456"), null, "精确值"),
new IndicatorDataItem(new BigDecimal("3.141592"), "/", "除以π"),
new IndicatorDataItem(new BigDecimal("2.718281"), "*", "乘以e")
);
BigDecimal result = IndicatorDataCalculatorUtil.calculateIndicator(dataItems, config);
4. 快速计算
// 快速计算:值列表 + 运算符列表
List<BigDecimal> values = Arrays.asList(
new BigDecimal("100"),
new BigDecimal("50"),
new BigDecimal("25"),
new BigDecimal("2")
);
List<String> operators = Arrays.asList("+", "-", "*");
BigDecimal result = IndicatorDataCalculatorUtil.quickCalculate(values, operators);
// 结果:100 + 50 - 25 * 2 = 100
5. 字符串表达式计算
// 解析字符串表达式
String expression = "100+50-25*2";
IndicatorCalculationConfig config = IndicatorDataCalculatorUtil.createDefaultConfig();
BigDecimal result = IndicatorDataCalculatorUtil.calculateFromExpression(expression, config);
// 结果:200.00
6. 获取详细计算结果
// 获取详细计算结果
IndicatorCalculationResult result = IndicatorDataCalculatorUtil.calculateIndicatorWithDetails(dataItems, config);
if (result.isSuccess()) {
System.out.println("最终结果: " + result.getFinalValue());
System.out.println("计算耗时: " + result.getCalculationTime() + "ms");
// 显示计算步骤
for (String step : result.getCalculationSteps()) {
System.out.println(step);
}
// 显示中间结果
for (BigDecimal intermediate : result.getIntermediateResults()) {
System.out.println(intermediate);
}
}
预定义配置
1. 默认配置
IndicatorCalculationConfig defaultConfig = IndicatorDataCalculatorUtil.createDefaultConfig();
// 精度: 2位小数
// 舍入模式: HALF_UP
// 允许负数: true
// 允许零值: true
// 严格模式: false
// 默认运算符: +
// 自动排序: true
2. 高精度配置
IndicatorCalculationConfig highPrecisionConfig = IndicatorDataCalculatorUtil.createHighPrecisionConfig();
// 精度: 6位小数
// 舍入模式: HALF_UP
3. 财务配置
IndicatorCalculationConfig financialConfig = IndicatorDataCalculatorUtil.createFinancialConfig();
// 精度: 2位小数
// 舍入模式: HALF_UP
// 允许负数: false
// 严格模式: true
实际应用场景
1. 招生系统指标计算
// 综合评分 = (基础分 + 加分 - 扣分) * 系数
List<IndicatorDataItem> enrollmentScoreItems = Arrays.asList(
new IndicatorDataItem(new BigDecimal("80"), null, "基础分"),
new IndicatorDataItem(new BigDecimal("15"), "+", "加分项"),
new IndicatorDataItem(new BigDecimal("5"), "-", "扣分项"),
new IndicatorDataItem(new BigDecimal("1.2"), "*", "系数调整")
);
BigDecimal enrollmentScore = IndicatorDataCalculatorUtil.calculateIndicator(enrollmentScoreItems);
2. 学生成绩计算
// 加权平均分计算
List<IndicatorDataItem> weightedScoreItems = Arrays.asList(
new IndicatorDataItem(new BigDecimal("85"), null, "语文成绩"),
new IndicatorDataItem(new BigDecimal("0.3"), "*", "语文权重"),
new IndicatorDataItem(new BigDecimal("92"), "+", "数学成绩"),
new IndicatorDataItem(new BigDecimal("0.4"), "*", "数学权重"),
new IndicatorDataItem(new BigDecimal("78"), "+", "英语成绩"),
new IndicatorDataItem(new BigDecimal("0.3"), "*", "英语权重")
);
BigDecimal weightedScore = IndicatorDataCalculatorUtil.calculateIndicator(weightedScoreItems);
3. 财务计算
// 利润计算:收入 - 成本 - 费用
List<IndicatorDataItem> profitItems = Arrays.asList(
new IndicatorDataItem(new BigDecimal("10000"), null, "收入"),
new IndicatorDataItem(new BigDecimal("6000"), "-", "成本"),
new IndicatorDataItem(new BigDecimal("2000"), "-", "费用")
);
IndicatorCalculationConfig config = IndicatorDataCalculatorUtil.createFinancialConfig();
BigDecimal profit = IndicatorDataCalculatorUtil.calculateIndicator(profitItems, config);
4. 统计分析
// 计算平均值
List<IndicatorDataItem> averageItems = Arrays.asList(
new IndicatorDataItem(new BigDecimal("255"), null, "总分"),
new IndicatorDataItem(new BigDecimal("3"), "/", "科目数")
);
BigDecimal average = IndicatorDataCalculatorUtil.calculateIndicator(averageItems);
运算符支持
工具类支持以下运算符:
+: 加法-: 减法*: 乘法/: 除法%: 取模^: 幂运算
计算规则
- 第一个数据项:不能有运算符,作为计算的起始值
- 后续数据项:必须指定运算符,表示与前一个结果的运算关系
- 计算顺序:按照数据项的顺序依次计算
- 精度控制:最终结果按照配置的小数位数进行舍入
- 错误处理:支持除零检查、负数限制等
性能特点
- 高效计算:优化的算法实现,支持大量数据计算
- 内存友好:使用
BigDecimal确保精度,避免浮点数问题 - 可扩展性:支持自定义运算符和计算逻辑
- 错误处理:完善的异常处理机制
注意事项
- 数据完整性:在严格模式下,所有数据项必须完整
- 运算符规范:第一个数据项不能有运算符
- 精度控制:根据业务需求选择合适的精度配置
- 异常处理:始终使用 try-catch 包装计算调用
扩展功能
工具类设计为可扩展的架构,可以根据需要添加:
- 新的运算符类型
- 自定义计算函数
- 特殊业务逻辑
- 缓存机制
- 并行计算支持
相关文件
IndicatorDataCalculatorUtil.java- 核心工具类
@Slf4j
public class IndicatorDataCalculatorUtil {
/**
* 指标数据项
*/
@Data
public static class IndicatorDataItem {
private BigDecimal value; // 实际值
private String operator; // 运算符(+、-、*、/、%)
private int order; // 计算顺序(可选,用于控制计算优先级)
private String description; // 描述信息
public IndicatorDataItem() {}
public IndicatorDataItem(BigDecimal value, String operator) {
this.value = value;
this.operator = operator;
}
public IndicatorDataItem(BigDecimal value, String operator, String description) {
this.value = value;
this.operator = operator;
this.description = description;
}
public IndicatorDataItem(BigDecimal value, String operator, int order, String description) {
this.value = value;
this.operator = operator;
this.order = order;
this.description = description;
}
}
/**
* 指标计算配置
*/
@Data
public static class IndicatorCalculationConfig {
private int scale = 2; // 保留小数位数
private RoundingMode roundingMode = RoundingMode.HALF_UP; // 舍入模式
private boolean allowNegative = true; // 是否允许负数
private boolean allowZero = true; // 是否允许零值
private boolean strictMode = false; // 严格模式(检查数据完整性)
private String defaultOperator = "+"; // 默认运算符
private boolean autoOrder = true; // 是否自动排序
public IndicatorCalculationConfig() {}
public IndicatorCalculationConfig(int scale, RoundingMode roundingMode) {
this.scale = scale;
this.roundingMode = roundingMode;
}
}
/**
* 指标计算结果
*/
@Data
public static class IndicatorCalculationResult {
private BigDecimal finalValue; // 最终计算结果
private List<BigDecimal> intermediateResults; // 中间计算结果
private List<String> calculationSteps; // 计算步骤说明
private boolean success; // 计算是否成功
private String errorMessage; // 错误信息
private long calculationTime; // 计算耗时(毫秒)
public IndicatorCalculationResult() {
this.intermediateResults = new ArrayList<>();
this.calculationSteps = new ArrayList<>();
}
}
/**
* 计算指标最终数值(基础版本)
*
* @param dataItems 指标数据项列表
* @return 计算结果
*/
public static BigDecimal calculateIndicator(List<IndicatorDataItem> dataItems) {
return calculateIndicator(dataItems, new IndicatorCalculationConfig());
}
/**
* 计算指标最终数值(带配置)
*
* @param dataItems 指标数据项列表
* @param config 计算配置
* @return 计算结果
*/
public static BigDecimal calculateIndicator(List<IndicatorDataItem> dataItems,
IndicatorCalculationConfig config) {
IndicatorCalculationResult result = calculateIndicatorWithDetails(dataItems, config);
if (!result.isSuccess()) {
throw new BusinessException("指标计算失败: " + result.getErrorMessage());
}
return result.getFinalValue();
}
/**
* 计算指标最终数值(返回详细结果)
*
* @param dataItems 指标数据项列表
* @param config 计算配置
* @return 详细计算结果
*/
public static IndicatorCalculationResult calculateIndicatorWithDetails(List<IndicatorDataItem> dataItems,
IndicatorCalculationConfig config) {
IndicatorCalculationResult result = new IndicatorCalculationResult();
long startTime = System.currentTimeMillis();
try {
// 参数验证
validateInput(dataItems, config);
// 数据预处理
List<IndicatorDataItem> processedItems = preprocessData(dataItems, config);
// 执行计算
BigDecimal finalValue = executeCalculation(processedItems, config, result);
// 设置结果
result.setFinalValue(finalValue);
result.setSuccess(true);
result.setCalculationTime(System.currentTimeMillis() - startTime);
} catch (Exception e) {
log.error("指标计算失败", e);
result.setSuccess(false);
result.setErrorMessage(e.getMessage());
result.setCalculationTime(System.currentTimeMillis() - startTime);
}
return result;
}
/**
* 快速计算(使用默认配置)
*
* @param values 数值列表
* @param operators 运算符列表
* @return 计算结果
*/
public static BigDecimal quickCalculate(List<BigDecimal> values, List<String> operators) {
if (values == null || values.isEmpty()) {
return BigDecimal.ZERO;
}
List<IndicatorDataItem> dataItems = new ArrayList<>();
// 第一个值不需要运算符
dataItems.add(new IndicatorDataItem(values.get(0), null));
// 后续值添加运算符
for (int i = 1; i < values.size(); i++) {
String operator = (i - 1 < operators.size()) ? operators.get(i - 1) : "+";
dataItems.add(new IndicatorDataItem(values.get(i), operator));
}
return calculateIndicator(dataItems);
}
/**
* 字符串表达式计算
*
* @param expression 表达式,如 "10+5*2-3"
* @param config 计算配置
* @return 计算结果
*/
public static BigDecimal calculateFromExpression(String expression, IndicatorCalculationConfig config) {
if (expression == null || expression.trim().isEmpty()) {
throw new BusinessException("表达式不能为空");
}
try {
List<IndicatorDataItem> dataItems = parseExpression(expression);
return calculateIndicator(dataItems, config);
} catch (Exception e) {
log.error("表达式解析失败: {}", expression, e);
throw new BusinessException("表达式解析失败: " + e.getMessage());
}
}
/**
* 创建默认配置
*/
public static IndicatorCalculationConfig createDefaultConfig() {
return new IndicatorCalculationConfig();
}
/**
* 创建高精度配置
*/
public static IndicatorCalculationConfig createHighPrecisionConfig() {
IndicatorCalculationConfig config = new IndicatorCalculationConfig();
config.setScale(6);
config.setRoundingMode(RoundingMode.HALF_UP);
return config;
}
/**
* 创建财务配置
*/
public static IndicatorCalculationConfig createFinancialConfig() {
IndicatorCalculationConfig config = new IndicatorCalculationConfig();
config.setScale(2);
config.setRoundingMode(RoundingMode.HALF_UP);
config.setAllowNegative(false);
config.setStrictMode(true);
return config;
}
/**
* 参数验证
*/
private static void validateInput(List<IndicatorDataItem> dataItems, IndicatorCalculationConfig config) {
if (dataItems == null || dataItems.isEmpty()) {
throw new BusinessException("指标数据项不能为空");
}
if (config == null) {
throw new BusinessException("计算配置不能为空");
}
// 检查第一个数据项是否有运算符
if (dataItems.get(0).getOperator() != null) {
throw new BusinessException("第一个数据项不能有运算符");
}
// 严格模式下的额外检查
if (config.isStrictMode()) {
for (int i = 0; i < dataItems.size(); i++) {
IndicatorDataItem item = dataItems.get(i);
if (item.getValue() == null) {
throw new BusinessException("第" + (i + 1) + "个数据项的值不能为空");
}
if (i > 0 && (item.getOperator() == null || item.getOperator().trim().isEmpty())) {
throw new BusinessException("第" + (i + 1) + "个数据项必须指定运算符");
}
}
}
}
/**
* 数据预处理
*/
private static List<IndicatorDataItem> preprocessData(List<IndicatorDataItem> dataItems,
IndicatorCalculationConfig config) {
List<IndicatorDataItem> processedItems = new ArrayList<>();
for (int i = 0; i < dataItems.size(); i++) {
IndicatorDataItem item = dataItems.get(i);
IndicatorDataItem processedItem = new IndicatorDataItem();
// 处理值
if (item.getValue() == null) {
if (config.isStrictMode()) {
throw new BusinessException("第" + (i + 1) + "个数据项的值不能为空");
}
processedItem.setValue(BigDecimal.ZERO);
} else {
processedItem.setValue(item.getValue());
}
// 处理运算符
if (i == 0) {
// 第一个项目不需要运算符
processedItem.setOperator(null);
} else {
if (item.getOperator() == null || item.getOperator().trim().isEmpty()) {
processedItem.setOperator(config.getDefaultOperator());
} else {
processedItem.setOperator(item.getOperator().trim());
}
}
processedItem.setOrder(item.getOrder());
processedItem.setDescription(item.getDescription());
processedItems.add(processedItem);
}
// 自动排序(如果启用)
if (config.isAutoOrder() && processedItems.size() > 1) {
processedItems.sort((a, b) -> Integer.compare(a.getOrder(), b.getOrder()));
}
return processedItems;
}
/**
* 执行计算
*/
private static BigDecimal executeCalculation(List<IndicatorDataItem> processedItems,
IndicatorCalculationConfig config,
IndicatorCalculationResult result) {
BigDecimal currentResult = processedItems.get(0).getValue();
result.getIntermediateResults().add(currentResult);
result.getCalculationSteps().add("初始值: " + currentResult);
for (int i = 1; i < processedItems.size(); i++) {
IndicatorDataItem item = processedItems.get(i);
BigDecimal nextValue = item.getValue();
String operator = item.getOperator();
BigDecimal previousResult = currentResult;
currentResult = performOperation(currentResult, nextValue, operator, config);
result.getIntermediateResults().add(currentResult);
result.getCalculationSteps().add(String.format("步骤%d: %s %s %s = %s",
i, previousResult, operator, nextValue, currentResult));
}
// 应用最终精度和舍入
currentResult = currentResult.setScale(config.getScale(), config.getRoundingMode());
// 应用配置限制
applyConfigLimits(currentResult, config);
return currentResult;
}
/**
* 执行具体运算
*/
private static BigDecimal performOperation(BigDecimal a, BigDecimal b, String operator,
IndicatorCalculationConfig config) {
switch (operator) {
case "+":
return a.add(b);
case "-":
return a.subtract(b);
case "*":
return a.multiply(b);
case "/":
if (b.compareTo(BigDecimal.ZERO) == 0) {
throw new BusinessException("除数不能为零");
}
return a.divide(b, config.getScale() + 2, config.getRoundingMode());
case "%":
if (b.compareTo(BigDecimal.ZERO) == 0) {
throw new BusinessException("取模运算的除数不能为零");
}
return a.remainder(b);
case "^":
return a.pow(b.intValue());
default:
throw new BusinessException("不支持的运算符: " + operator);
}
}
/**
* 应用配置限制
*/
private static void applyConfigLimits(BigDecimal result, IndicatorCalculationConfig config) {
if (!config.isAllowNegative() && result.compareTo(BigDecimal.ZERO) < 0) {
throw new BusinessException("计算结果为负数,但配置不允许负数");
}
if (!config.isAllowZero() && result.compareTo(BigDecimal.ZERO) == 0) {
throw new BusinessException("计算结果为零,但配置不允许零值");
}
}
/**
* 解析表达式
*/
private static List<IndicatorDataItem> parseExpression(String expression) {
List<IndicatorDataItem> dataItems = new ArrayList<>();
// 移除所有空格
expression = expression.replaceAll("\\s+", "");
// 使用正则表达式分割
String[] parts = expression.split("(?<=[-+*/%^])|(?=[-+*/%^])");
if (parts.length == 0) {
throw new BusinessException("表达式格式错误");
}
// 第一个部分必须是数字
if (!isNumber(parts[0])) {
throw new BusinessException("表达式必须以数字开始");
}
dataItems.add(new IndicatorDataItem(new BigDecimal(parts[0]), null));
for (int i = 1; i < parts.length; i += 2) {
if (i + 1 >= parts.length) {
throw new BusinessException("表达式格式不完整");
}
String operator = parts[i];
String number = parts[i + 1];
if (!isOperator(operator)) {
throw new BusinessException("无效的运算符: " + operator);
}
if (!isNumber(number)) {
throw new BusinessException("无效的数字: " + number);
}
dataItems.add(new IndicatorDataItem(new BigDecimal(number), operator));
}
return dataItems;
}
/**
* 判断是否为数字
*/
private static boolean isNumber(String str) {
try {
new BigDecimal(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
/**
* 判断是否为运算符
*/
private static boolean isOperator(String str) {
return str.matches("[-+*/%^]");
}
/**
* 创建指标数据项构建器
*/
public static class IndicatorDataItemBuilder {
private List<IndicatorDataItem> items = new ArrayList<>();
public IndicatorDataItemBuilder addValue(BigDecimal value) {
if (items.isEmpty()) {
items.add(new IndicatorDataItem(value, null));
} else {
items.add(new IndicatorDataItem(value, "+"));
}
return this;
}
public IndicatorDataItemBuilder addValue(BigDecimal value, String operator) {
items.add(new IndicatorDataItem(value, operator));
return this;
}
public IndicatorDataItemBuilder addValue(BigDecimal value, String operator, String description) {
items.add(new IndicatorDataItem(value, operator, description));
return this;
}
public List<IndicatorDataItem> build() {
return new ArrayList<>(items);
}
}
/**
* 获取构建器实例
*/
public static IndicatorDataItemBuilder builder() {
return new IndicatorDataItemBuilder();
}
}
IndicatorDataCalculatorUtilExample.java- 使用示例
public class IndicatorCalculatorUtilExample {
/**
* 示例1:基础四则运算
*/
public static void basicOperationsExample() {
System.out.println("=== 基础四则运算示例 ===");
BigDecimal a = new BigDecimal("100.50");
BigDecimal b = new BigDecimal("25.25");
// 加法
BigDecimal sum = IndicatorCalculatorUtil.calculate(a, b, IndicatorCalculatorUtil.Operator.ADD);
System.out.println("加法: " + a + " + " + b + " = " + sum);
// 减法
BigDecimal difference = IndicatorCalculatorUtil.calculate(a, b, IndicatorCalculatorUtil.Operator.SUBTRACT);
System.out.println("减法: " + a + " - " + b + " = " + difference);
// 乘法
BigDecimal product = IndicatorCalculatorUtil.calculate(a, b, IndicatorCalculatorUtil.Operator.MULTIPLY);
System.out.println("乘法: " + a + " * " + b + " = " + product);
// 除法
BigDecimal quotient = IndicatorCalculatorUtil.calculate(a, b, IndicatorCalculatorUtil.Operator.DIVIDE);
System.out.println("除法: " + a + " / " + b + " = " + quotient);
}
/**
* 示例2:字符串表达式计算
*/
public static void stringExpressionExample() {
System.out.println("\n=== 字符串表达式计算示例 ===");
// 简单表达式
String expression1 = "10 + 5 * 2";
BigDecimal result1 = IndicatorCalculatorUtil.calculate(expression1);
System.out.println("表达式: " + expression1 + " = " + result1);
// 带括号的表达式
String expression2 = "(10 + 5) * 2";
BigDecimal result2 = IndicatorCalculatorUtil.calculate(expression2);
System.out.println("表达式: " + expression2 + " = " + result2);
// 复杂表达式
String expression3 = "100 / (5 + 3) * 2 - 10";
BigDecimal result3 = IndicatorCalculatorUtil.calculate(expression3);
System.out.println("表达式: " + expression3 + " = " + result3);
}
/**
* 示例3:自定义配置计算
*/
public static void customConfigExample() {
System.out.println("\n=== 自定义配置计算示例 ===");
// 创建高精度配置
IndicatorCalculatorUtil.IndicatorConfig highPrecisionConfig =
IndicatorCalculatorUtil.createHighPrecisionConfig();
BigDecimal a = new BigDecimal("10.123456");
BigDecimal b = new BigDecimal("3.141592");
BigDecimal result = IndicatorCalculatorUtil.calculate(a, b,
IndicatorCalculatorUtil.Operator.DIVIDE, highPrecisionConfig);
System.out.println("高精度除法: " + a + " / " + b + " = " + result);
// 创建财务配置(不允许负数)
IndicatorCalculatorUtil.IndicatorConfig financialConfig =
IndicatorCalculatorUtil.createFinancialConfig();
try {
BigDecimal negativeResult = IndicatorCalculatorUtil.calculate(b, a,
IndicatorCalculatorUtil.Operator.SUBTRACT, financialConfig);
System.out.println("财务计算: " + b + " - " + a + " = " + negativeResult);
} catch (Exception e) {
System.out.println("财务计算不允许负数: " + e.getMessage());
}
}
/**
* 示例4:批量计算
*/
public static void batchCalculationExample() {
System.out.println("\n=== 批量计算示例 ===");
List<BigDecimal> scores = Arrays.asList(
new BigDecimal("85.5"),
new BigDecimal("92.3"),
new BigDecimal("78.9"),
new BigDecimal("95.1"),
new BigDecimal("88.7")
);
// 计算总分
BigDecimal totalScore = IndicatorCalculatorUtil.calculateBatch(
scores,
score -> score,
IndicatorCalculatorUtil.Operator.ADD,
IndicatorCalculatorUtil.createDefaultConfig()
);
System.out.println("总分: " + totalScore);
// 计算平均分
BigDecimal averageScore = IndicatorCalculatorUtil.calculateAverage(
scores,
IndicatorCalculatorUtil.createDefaultConfig()
);
System.out.println("平均分: " + averageScore);
}
/**
* 示例5:加权计算
*/
public static void weightedCalculationExample() {
System.out.println("\n=== 加权计算示例 ===");
// 学生各科成绩
List<BigDecimal> scores = Arrays.asList(
new BigDecimal("85"), // 语文
new BigDecimal("92"), // 数学
new BigDecimal("78"), // 英语
new BigDecimal("95") // 综合
);
// 各科权重
List<BigDecimal> weights = Arrays.asList(
new BigDecimal("0.25"), // 语文25%
new BigDecimal("0.35"), // 数学35%
new BigDecimal("0.20"), // 英语20%
new BigDecimal("0.20") // 综合20%
);
BigDecimal weightedAverage = IndicatorCalculatorUtil.calculateWeightedAverage(
scores, weights, IndicatorCalculatorUtil.createDefaultConfig()
);
System.out.println("加权平均分: " + weightedAverage);
}
/**
* 示例6:增长率计算
*/
public static void growthRateExample() {
System.out.println("\n=== 增长率计算示例 ===");
// 学生成绩增长
BigDecimal currentScore = new BigDecimal("92");
BigDecimal previousScore = new BigDecimal("85");
BigDecimal growthRate = IndicatorCalculatorUtil.calculateGrowthRate(
currentScore, previousScore, IndicatorCalculatorUtil.createDefaultConfig()
);
System.out.println("成绩增长率: " + growthRate + "%");
// 复合增长率(多期)
BigDecimal initialValue = new BigDecimal("1000");
BigDecimal finalValue = new BigDecimal("1331");
int periods = 3;
BigDecimal compoundGrowthRate = IndicatorCalculatorUtil.calculateCompoundGrowthRate(
initialValue, finalValue, periods, IndicatorCalculatorUtil.createDefaultConfig()
);
System.out.println("复合增长率: " + compoundGrowthRate);
}
/**
* 示例7:实际业务场景
*/
public static void businessScenarioExample() {
System.out.println("\n=== 实际业务场景示例 ===");
// 模拟招生指标计算
BigDecimal totalApplicants = new BigDecimal("1000");
BigDecimal acceptedApplicants = new BigDecimal("800");
BigDecimal rejectedApplicants = new BigDecimal("200");
// 计算录取率
BigDecimal acceptanceRate = IndicatorCalculatorUtil.calculate(
acceptedApplicants, totalApplicants, IndicatorCalculatorUtil.Operator.DIVIDE
).multiply(new BigDecimal("100"));
System.out.println("录取率: " + acceptanceRate + "%");
// 计算拒绝率
BigDecimal rejectionRate = IndicatorCalculatorUtil.calculate(
rejectedApplicants, totalApplicants, IndicatorCalculatorUtil.Operator.DIVIDE
).multiply(new BigDecimal("100"));
System.out.println("拒绝率: " + rejectionRate + "%");
// 验证总和是否为100%
BigDecimal totalRate = acceptanceRate.add(rejectionRate);
System.out.println("总比率: " + totalRate + "%");
}
/**
* 主方法,运行所有示例
*/
public static void main(String[] args) {
try {
basicOperationsExample();
stringExpressionExample();
customConfigExample();
batchCalculationExample();
weightedCalculationExample();
growthRateExample();
businessScenarioExample();
System.out.println("\n=== 所有示例执行完成 ===");
} catch (Exception e) {
System.err.println("示例执行出错: " + e.getMessage());
e.printStackTrace();
}
}
}

被折叠的 条评论
为什么被折叠?



