package com.ruoyi.production.utils;
|
|
import java.math.BigDecimal;
|
import java.math.RoundingMode;
|
import java.util.Arrays;
|
import java.util.HashSet;
|
import java.util.Set;
|
|
/**
|
* <br>
|
* 单位转换工具类
|
* </br>
|
*
|
* @author deslrey
|
* @version 1.0
|
* @since 2026/03/30 15:07
|
*/
|
public class UnitUtils {
|
|
private static final Set<String> WEIGHT_UNITS = new HashSet<>(Arrays.asList(
|
"千克", "公斤", "kg", "KG", "kG",
|
"克", "g", "G",
|
"吨", "t", "T"
|
));
|
|
private static final Set<String> KG_UNITS = new HashSet<>(Arrays.asList("千克", "公斤", "kg", "KG", "kG"));
|
private static final Set<String> G_UNITS = new HashSet<>(Arrays.asList("克", "g", "G"));
|
private static final Set<String> TON_UNITS = new HashSet<>(Arrays.asList("吨", "t", "T"));
|
|
/**
|
* 判断是否为重量单位
|
*/
|
public static boolean isWeightUnit(String unit) {
|
return unit != null && WEIGHT_UNITS.contains(unit.trim());
|
}
|
|
/**
|
* 如果是重量单位,统一返回“吨”,否则返回原单位
|
*/
|
public static String normalizeUnit(String unit) {
|
if (isWeightUnit(unit)) {
|
return "吨";
|
}
|
return unit != null ? unit.trim() : "未知单位";
|
}
|
|
/**
|
* 如果是重量单位,折算为“吨”,否则返回原值
|
*/
|
public static BigDecimal convertValueToTon(BigDecimal value, String unit) {
|
if (value == null || unit == null) {
|
return value != null ? value : BigDecimal.ZERO;
|
}
|
|
String trimmedUnit = unit.trim();
|
if (KG_UNITS.contains(trimmedUnit)) {
|
return value.divide(new BigDecimal("1000"), 6, RoundingMode.HALF_UP);
|
} else if (G_UNITS.contains(trimmedUnit)) {
|
return value.divide(new BigDecimal("1000000"), 6, RoundingMode.HALF_UP);
|
} else if (TON_UNITS.contains(trimmedUnit)) {
|
return value;
|
}
|
|
return value;
|
}
|
}
|