decimal保留小数位数 向上或向下取
1 public class DecimalHelper 2 { 3 /// <summary> 4 /// Decimal类型截取保留N位小数并且不进行四舍五入操作 5 /// </summary> 6 /// <param name="d"></param> 7 /// <param name="n"></param> 8 /// <returns></returns> 9 public static decimal CutDecimalWithN(decimal d, int n) 10 { 11 string strDecimal = d.ToString(); 12 int index = strDecimal.IndexOf("."); 13 if (index == -1 || strDecimal.Length < index + n + 1) 14 { 15 strDecimal = string.Format("{0:F" + n + "}", d); 16 } 17 else 18 { 19 int length = index; 20 if (n != 0) 21 { 22 length = index + n + 1; 23 } 24 strDecimal = strDecimal.Substring(0, length); 25 } 26 return Decimal.Parse(strDecimal); 27 } 28 29 /// <summary> 30 /// Decimal类型截取保留N位小数向上取 31 /// </summary> 32 /// <param name="d"></param> 33 /// <param name="n"></param> 34 /// <returns></returns> 35 public static decimal Ceiling(decimal d, int n) 36 { 37 decimal t = decimal.Parse(Math.Pow(10, n).ToString()); 38 d = Math.Ceiling(t * d); 39 return d / t; 40 } 41 }