C# 四舍五入 进一法 直接取整 带小数位数
[一篮饭特稀原创,转载请注明出处http://www.cnblogs.com/wanghafan/archive/2012/05/18/2508113.html]
四舍五入
View Code
1 public static decimal Round(decimal d, decimal unit) 2 { 3 decimal rm = d % unit; 4 decimal result = d - rm; 5 if (rm >= unit / 2) 6 result += unit; 7 return result; 8 }
进一法
View Code
1 public static decimal Jinyi(decimal d, decimal unit) 2 { 3 decimal rm = d % unit; 4 decimal result = d - rm; 5 if (rm > 0) 6 result += unit; 7 return result; 8 }
直接取整
View Code
1 public static decimal Quzheng(decimal d, decimal unit) 2 { 3 decimal rm = d % unit; 4 decimal result = d - rm; 5 return result; 6 }
调用方式
View Code
1 int cou = 3; 2 string uit = string.Empty; 3 int cou = int.Parse(dt.Rows[0]["小数位数"].ToString()); 4 if (cou == 0) 5 { 6 uit = "1"; 7 } 8 else 9 { 10 uit = "0."; 11 for (int i = 1; i < cou; i++) 12 uit += "0"; 13 uit += "1"; 14 } 15 16 Jinyi(num, decimal.Parse(uit)); 17 Round(num, decimal.Parse(uit)); 18 Quzheng(num, decimal.Parse(uit));