public static class DecimalHelper
{
public static decimal CutDecimalWithN(decimal d, int n)
{
string strDecimal = d.ToString();
int index = strDecimal.IndexOf(".");
if (index == -1 || strDecimal.Length < index + n + 1)
{
strDecimal = string.Format("{0:F" + n + "}", d);
}
else
{
int length = index;
if(n != 0)
{
length = index + n + 1;
}
strDecimal = strDecimal.Substring(0, length);
}
return Decimal.Parse(strDecimal);
}
}
decimal d = 1.23456789M;
for (int i = 0; i <= 10; i++)
{
Console.WriteLine("{0}", DecimalHelper.CutDecimalWithN(d, i));
}
for (int i = 0; i <= 10; i++)
{
Console.WriteLine("{0}", Decimal.Round(d, i));
}
C#使Decimal类型数据保留N位小数且不进行四舍五入操作
最新推荐文章于 2022-09-22 16:31:46 发布