欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#之如何實現(xiàn)真正的四舍五入

 更新時間:2023年05月04日 11:02:32   作者:xiaososa.  
這篇文章主要介紹了C#之如何實現(xiàn)真正的四舍五入問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

C#實現(xiàn)真正的四舍五入

C#中的Math.Round()直接使用的話,實際上是:四舍六入五取偶,并不是真正意義上的四舍五入。

例如 我取2位小數(shù) 17.365

會變成17.36 很苦惱

實現(xiàn)真正四舍五入需要用到 MidpointRounding.AwayFromZero 枚舉項,同時傳入的數(shù)值類型必須是decimal類型:

用法示例:

 decimal dd= Math.Round((decimal)66.545, 2, MidpointRounding.AwayFromZero);

還有2種比較殘暴的 寫個函數(shù) 正負數(shù)都可以四舍五入或者負數(shù)五舍六入

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;
}

參數(shù):d表示要四舍五入的數(shù);i表示要保留的小數(shù)點后為數(shù)。

其中第二種方法是正負數(shù)都四舍五入,第一種方法是正數(shù)四舍五入,負數(shù)是五舍六入。

備注:個人認為第一種方法適合處理貨幣計算,而第二種方法適合數(shù)據(jù)統(tǒng)計的顯示。

C#簡單四舍五入函數(shù)

public int getNum(double t) {?
? ? ? ? ? ? double t1;
? ? ? ? ? ? int t2;
? ? ? ? ? ? string[] s = t.ToString().Split('.');
? ? ? ? ? ? string i = s[1].Substring(0, 1);//取得第一位小數(shù)
? ? ? ? ? ? int j = Convert.ToInt32(i);
? ? ? ? ? ? if (j >= 5)
? ? ? ? ? ? ? ? t1 = Math.Ceiling(t); //向上 轉(zhuǎn)換
? ? ? ? ? ? else
? ? ? ? ? ? ? ? t1 = Math.Floor(t);// 向下 轉(zhuǎn)換
? ? ? ? ? ? t2 = (int)t1;
? ? ? ? ? ? return t2;
? ? ? ? }
  • Convert.ToInt32(1.2)  為四舍五入 的強制轉(zhuǎn)換 但是 0.5時候 會為 0
  • (int) 1.2  是向下強制轉(zhuǎn)換既Math.Floor(),1.2轉(zhuǎn)換后為1;
  • Math.Ceiling(1.2)則是向上轉(zhuǎn)換,得到2。

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論