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位小数且不进行四舍五入操作
最新推荐文章于 2025-02-27 10:13:30 发布
这个博客展示了如何在C#中使用DecimalHelper类来精确地截取和四舍五入小数值到指定的小数位数。示例代码演示了对于1.23456789M这个decimal值,如何在0到10位之间进行操作。此外,还对比了使用Decimal.Round方法进行四舍五入的效果。
4万+

被折叠的 条评论
为什么被折叠?



