Files
gzh-server/src/main/java/com/guahao/common/util/AmountUtil.java
2026-01-15 16:25:58 +08:00

75 lines
2.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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);
}
// Double金额转为String金额
public static String doubleToStr(Double amount) {
return String.format("%.2f", amount);
}
}