.net 四舍五入

来源:互联网 发布:上海视频会议软件 编辑:程序博客网 时间:2024/04/29 10:48

C# 中没有四舍五入函数,程序语言都没有四舍五入函数,因为四舍五入算法不科学,国际通行的是 Banker 舍入法
Bankers rounding(银行家舍入)算法,即四舍六入五取偶。事实上这也是 IEEE 规定的舍入标准。因此所有符合 IEEE 标准的语言都应该是采用这一算法的
Math.Round 方法默认的也是 Banker 舍入法
因此需要自己写个函数来处理
第一个函数:
double Round(double value, int decimals)
{
  if (value < 0)
  {
    return Math.Round(value + 5 / Math.Pow(10, decimals + 1), decimals, MidpointRounding.AwayFromZero);
  }
  else
  {
    return Math.Round(value, decimals, MidpointRounding.AwayFromZero);
  }
}

第二个函数:
double Round(double d, int i)
{
  if(d >=0)
  {
    d += 5 * Math.Pow(10, -(i + 1));
  }
  else
  {
    d += -5 * Math.Pow(10, -(i + 1));
  }
  string str = d.ToString();
  string[] strs = str.Split('.');
  int idot = str.IndexOf('.');
  string prestr = strs[0];
  string poststr = strs[1];
  if(poststr.Length > i)
  {
    poststr = str.Substring(idot + 1, i);
  }
  string strd = prestr + "." + poststr;
  d = Double.Parse(strd);
  return d;
}

参数:d表示要四舍五入的数;i表示要保留的小数点后为数。

其中第二种方法是正负数都四舍五入,第一种方法是正数四舍五入,负数是五舍六入。

备注:个人认为第一种方法适合处理货币计算,而第二种方法适合数据统计的显示。

原创粉丝点击