- toUpAmountConversion()金额向上转换
- calculationRatio()计算比率
- moneyFormat()金额格式化
- rateFormat()百分比格式化
- cleanUnnecessaryZero()去除小数点后多余的0
package com.ywz.common;import lombok.extern.slf4j.Slf4j;import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Objects;/*** 类描述 -> 数字工具类* toUpAmountConversion()金额向上转换* calculationRatio()计算比率* moneyFormat()金额格式化* rateFormat()百分比格式化* cleanUnnecessaryZero()去除小数点后多余的0* @Author: ywz* @Date: 2024/11/07*/
@Slf4j
public class NumberUtils {/*** 方法描述 -> 金额向上转换方法 元 -> 万元,万元 -> 亿元,默认4位小数** @param amount 金额* @Author: ywz* @Date: 2024/10/27*/public static BigDecimal toUpAmountConversion(BigDecimal amount) {return toUpAmountConversion(amount, 4);}public static BigDecimal toUpAmountConversion(BigDecimal amount, int scale) {if (StringUtils.isNull(amount)) {log.error("金额不能为空");return null;}return amount.divide(new BigDecimal("10000"), scale, RoundingMode.HALF_UP);}/*** 方法描述 -> 计算比率,默认2位小数** @param dividend 被除数* @param divider 除数* @Author: ywz* @Date: 2024/10/28*/public static BigDecimal calculationRatio(BigDecimal dividend, BigDecimal divider) {return calculationRatio(dividend, divider, 4);}public static BigDecimal calculationRatio(BigDecimal dividend, BigDecimal divider, int scale) {if (StringUtils.isNull(dividend, divider)) {log.error("被除数或除数不能为空");return null;}if (divider.compareTo(BigDecimal.ZERO) == 0) {log.error("除数不能为0");return null;}return dividend.divide(divider, scale, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));}/*** 方法描述 -> 金额格式化* 100 -> ¥100.00* @param amount 金额* @Author: ywz* @Date: 2024/11/07*/public static String moneyFormat(BigDecimal amount) {NumberFormat currencyInstance = NumberFormat.getCurrencyInstance();if (Objects.isNull(amount))return currencyInstance.format(0);return currencyInstance.format(amount);}/*** 方法描述 -> 百分比格式化* 0.01 -> 1%* @param rate 比率* @Author: ywz* @Date: 2024/11/07*/public static String rateFormat(BigDecimal rate) {NumberFormat percentInstance = NumberFormat.getPercentInstance();if (Objects.isNull(rate))return percentInstance.format(0);return percentInstance.format(rate);}/*** 方法描述 -> 去除小数点后多余的0** @param decimal 小数* @Author: ywz* @Date: 2024/11/07*/public static String cleanUnnecessaryZero(BigDecimal decimal) {if (Objects.isNull(decimal))return null;return decimal.stripTrailingZeros().toPlainString();}
}