1.代码实现
/// <summary>
/// 保留小数位数,实现四舍五入
/// </summary>
/// <param name="number">数字</param>
/// <param name="decimalNumber">保留位数</param>
/// <returns></returns>
private decimal SignificantDecimal(decimal number, int decimalNumber)
{
string numberStr = number.ToString();
int dotIndex = numberStr.IndexOf('.');
if (dotIndex < 0)
{
return number;
}
int firstNoneZeroIndex = numberStr.IndexOfAny(new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9' });
int beginIndex = 0;
if (dotIndex < firstNoneZeroIndex)
{
beginIndex = firstNoneZeroIndex;
}
else
{
beginIndex = dotIndex + 1;
}
decimal result = Round(number, beginIndex - dotIndex + decimalNumber - 1);
return result;
}
private decimal Round(decimal number, int decimalNumber)
{
return Math.Round(number, decimalNumber, MidpointRounding.AwayFromZero);
}
2. 使用
decimal mj1 = SignificantDecimal(0.224,2);