C#四舍五入类
作者:C/S框架网  发布日期:2015-01-04 19:59:52
  C#四舍五入类


注: 该类中3个静态方法未经本人测试


C# Code:

/// <summary>
/// 四舍五入类
/// </summary>
public class MathRound
{
   /// <summary>
   /// 实现数据的四舍五入法
   /// </summary>
   /// <param name="v">要进行处理的数据</param>
   /// <param name="x">保留的小数位数</param>
   /// <returns>四舍五入后的结果</returns>
   public static double Round(double v, int x)
   {
      bool isNegative = false;
      //如果是负数
      if (v < 0)
      {
         isNegative = true;
         v = -v;
      }
      
      int IValue = 1;
      for (int i = 1; i <= x; i )
      {
         IValue = IValue * 10;
      }
      double Int = Math.Round(v * IValue 0.5, 0);
      v = Int / IValue;
      
      if (isNegative)
      {
         v = -v;
      }
      
      return v;
   }
   
   /// <summary>
   /// 实现数据的舍去发
   /// </summary>
   /// <param name="v">要进行处理的数据</param>
   /// <param name="x">保留的小数位数</param>
   /// <returns>舍去后的结果</returns>
   public static double RoundRej(double v, int x)
   {
      //v = 1.224;
      string[] part = v.ToString().Split('.');
      if (part.Length == 1) return v;
      
      part[1] = part[1].PadRight(x, '0').Substring(0, x);
      double dd = double.Parse(part[0] "." part[1]);
      return dd;
      
   }
   
   /// <summary>
   /// 实现数据的进一发
   /// </summary>
   /// <param name="v">要进行处理的数据</param>
   /// <param name="x">保留的小数位数</param>
   /// <returns>进一的结果</returns>
   public double RoundIn(double v, int x)
   {
      //如果是负数
      if (v < 0) v = -v;
      
      int IValue = 1;
      for (int i = 1; i <= x 1; i )
      {
         IValue = IValue * 10;
      }
      double Int = Math.Round(v 5.00 / IValue, x, MidpointRounding.AwayFromZero);
      
      return Int;
   }
   
}

//来源:C/S框架网(www.csframework.com) QQ:1980854898


上一篇 下一篇