You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.8 KiB
C#

2 years ago
namespace DS.Module.Core;
/// <summary>
/// Decimal 工具类
/// </summary>
public static class DecimalUtil
{
/// <summary>
/// 获得decimal的精度
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static int Precise(this decimal value)
{
var s = value.ToString();
if (!s.Contains('.'))
{
return 0;
}
return s.Length - s.IndexOf('.') - 1;
}
/// <summary>
/// 检查金额, 最大值为8位数字
/// </summary>
/// <param name="money">金额</param>
/// <param name="title">标题</param>
/// <param name="ignoreMax">是否忽略最大值检查 默认为否</param>
/// <param name="digit">小数位数</param>
/// <returns></returns>
public static (bool isSuccess, string errMsg) CheckMoney(this decimal money, string title, bool ignoreMax = false,
int maxDigit = 8, int digit = 3)
{
// 0或者负数检查
if (money <= 0M)
{
return (false, $"{title}不为0或负");
}
// 最大值检查
if (!ignoreMax)
{
decimal maximum = NumberConst.MAX_8;
switch (maxDigit)
{
case 5:
maximum = NumberConst.MAX_5;
break;
default:
maximum = NumberConst.MAX_8;
break;
}
if (money > maximum)
{
return (false, $"{title}不能超过最大值");
}
}
// 两位有效小数检查
int precise = money.Precise();
if (precise > digit)
{
return (false, $"{title}位数超出范围");
//return (false, $"{title}最多有两位小数");
}
return (true, string.Empty);
}
}