71 lines
2.3 KiB
Java
71 lines
2.3 KiB
Java
|
|
package com.guahao.common.util;
|
|||
|
|
|
|||
|
|
import java.math.BigDecimal;
|
|||
|
|
import java.math.RoundingMode;
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 金额处理工具类
|
|||
|
|
*/
|
|||
|
|
public final class AmountUtil {
|
|||
|
|
|
|||
|
|
private AmountUtil() {
|
|||
|
|
throw new AssertionError("No instances for utility class");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 将字符串金额转换为 BigDecimal
|
|||
|
|
* 支持格式: "123", "123.45", " 123.45 ", "-123.45", "+123.45"
|
|||
|
|
*
|
|||
|
|
* @param amountStr 金额字符串
|
|||
|
|
* @return BigDecimal 对象,如果输入为 null 或无效格式,返回 BigDecimal.ZERO
|
|||
|
|
*/
|
|||
|
|
public static BigDecimal parseAmount(String amountStr) {
|
|||
|
|
return parseAmount(amountStr, BigDecimal.ZERO);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 将字符串金额转换为 BigDecimal,支持指定默认值
|
|||
|
|
*
|
|||
|
|
* @param amountStr 金额字符串
|
|||
|
|
* @param defaultValue 解析失败时返回的默认值
|
|||
|
|
* @return BigDecimal 对象
|
|||
|
|
*/
|
|||
|
|
public static BigDecimal parseAmount(String amountStr, BigDecimal defaultValue) {
|
|||
|
|
if (amountStr == null || amountStr.trim().isEmpty()) {
|
|||
|
|
return defaultValue;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
return new BigDecimal(amountStr.trim());
|
|||
|
|
} catch (NumberFormatException e) {
|
|||
|
|
System.err.println("金额格式错误: " + amountStr);
|
|||
|
|
return defaultValue;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 将字符串金额转换为 BigDecimal,并指定小数位数和舍入模式
|
|||
|
|
*
|
|||
|
|
* @param amountStr 金额字符串
|
|||
|
|
* @param scale 保留小数位数(如 2 表示保留两位小数)
|
|||
|
|
* @param roundingMode 舍入模式,如 RoundingMode.HALF_UP(四舍五入)
|
|||
|
|
* @return BigDecimal 对象,格式错误或 null 返回 0.00
|
|||
|
|
*/
|
|||
|
|
public static BigDecimal parseAmount(String amountStr, int scale, RoundingMode roundingMode) {
|
|||
|
|
BigDecimal amount = parseAmount(amountStr, BigDecimal.ZERO);
|
|||
|
|
return amount.setScale(scale, roundingMode);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 安全比较两个金额字符串大小
|
|||
|
|
*
|
|||
|
|
* @param a 金额A
|
|||
|
|
* @param b 金额B
|
|||
|
|
* @return a > b 返回 1, a < b 返回 -1, a == b 返回 0
|
|||
|
|
*/
|
|||
|
|
public static int compare(String a, String b) {
|
|||
|
|
BigDecimal amountA = parseAmount(a, BigDecimal.ZERO);
|
|||
|
|
BigDecimal amountB = parseAmount(b, BigDecimal.ZERO);
|
|||
|
|
return amountA.compareTo(amountB);
|
|||
|
|
}
|
|||
|
|
}
|