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