Decimal类型截取保留N位小数向上取
Decimal类型截取保留N位小数并且不进行四舍五入操作
封装静态方法
public class DecimalHelper { /// <summary> /// Decimal类型截取保留N位小数并且不进行四舍五入操作 /// </summary> /// <param name="d"></param> /// <param name="n"></param> /// <returns></returns> 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); } /// <summary> /// Decimal类型截取保留N位小数向上取 /// </summary> /// <param name="d"></param> /// <param name="n"></param> /// <returns></returns> public static decimal Ceiling(decimal d, int n) { decimal t = decimal.Parse(Math.Pow(10, n).ToString()); d = Math.Ceiling(t * d); return d / t; } }
测试方法:
class Program { static void Main(string[] args) { Console.WriteLine(); decimal Dec = 12.12345M; for (int i = 0; i < 10; i++) { Console.WriteLine($"{Dec} 保留{i} 位小数不进行四舍五入操作:" + DecimalHelper.CutDecimalWithN(Dec, i)); } Console.WriteLine(); for (int i = 0; i < 10; i++) { Console.WriteLine($"{Dec} 保留{i} 位小数向上取整操作:" + DecimalHelper.Ceiling(Dec, i)); } Console.Read(); } }