namespace Easy.Core;
///
/// 金额处理工具类
/// 统一处理货币单位转换、精度控制和四舍五入规则
///
public static class AmountHelper
{
///
/// 金额精度小数位数
///
private const int DecimalPlaces = 2;
///
/// 将元转换为分
///
/// 金额(元)
/// 金额(分)
public static int YuanToFen(decimal amount)
{
var roundedAmount = Math.Round(amount, DecimalPlaces, MidpointRounding.AwayFromZero);
return (int)Math.Round(roundedAmount * 100, MidpointRounding.AwayFromZero);
}
///
/// 将分转换为元
///
/// 金额(分)
/// 金额(元)
public static decimal FenToYuan(int amount)
{
return amount / 100m;
}
///
/// 将分转换为元(可为空)
///
/// 金额(分)
/// 金额(元)
public static decimal? FenToYuan(int? amount)
{
if (!amount.HasValue) return null;
return amount.Value / 100m;
}
///
/// 四舍五入金额到指定小数位
///
/// 金额
/// 小数位数,默认2位
/// 四舍五入后的金额
public static decimal Round(decimal amount, int decimalPlaces = DecimalPlaces)
{
return Math.Round(amount, decimalPlaces, MidpointRounding.AwayFromZero);
}
///
/// 验证金额格式是否正确(最多保留2位小数)
///
/// 金额
/// 是否有效
public static bool IsValidAmount(decimal amount)
{
var rounded = Math.Round(amount, DecimalPlaces, MidpointRounding.AwayFromZero);
return rounded == amount;
}
///
/// 验证金额是否大于0且格式正确
///
/// 金额
/// 是否有效
public static bool IsValidPositiveAmount(decimal amount)
{
return amount > 0 && IsValidAmount(amount);
}
}