C#四舍五入MidpointRounding.AwayFromZero解析
更新時間:2023年05月04日 11:10:20 作者:王源駿
這篇文章主要介紹了C#四舍五入MidpointRounding.AwayFromZero,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
C#四舍五入MidpointRounding.AwayFromZero
四舍五入 在計算中 經常使用到,但是如果使用 Math.Round,只是五舍六入
在Math.Round內傳入MidpointRounding.AwayFromZero枚舉,就可以實現四舍五入的效果了,
Debug.Log($"四舍五入{66.6}。。。{(int)Math.Round(66.6, MidpointRounding.AwayFromZero)}");
Debug.Log($"四舍五入{66.5}。。。{(int)Math.Round(66.5, MidpointRounding.AwayFromZero)}");
Debug.Log($"四舍五入{66.4}。。。{(int)Math.Round(66.4, MidpointRounding.AwayFromZero)}");
Debug.Log($"四舍五入{66.6}。。。{(int)Math.Round(66.6)}");
Debug.Log($"四舍五入{66.5}。。。{(int)Math.Round(66.5)}");
Debug.Log($"四舍五入{66.4}。。。{(int)Math.Round(66.4)}");
C#文檔:
C#四舍五入以及保留小數位的方法
C#中的Math.Round()并不是使用的"四舍五入"法。
其實C#的Round函數都是采用Banker’s rounding(銀行家算法),即:四舍六入五取偶
Math.Round(0.4) //result:0 Math.Round(0.6) //result:1 Math.Round(0.5) //result:0 Math.Round(1.5) //result:2 Math.Round(2.5) //result:2
使用MidpointRounding.AwayFromZero的效果:
Math.Round(0.4, MidpointRounding.AwayFromZero); // result:0 Math.Round(0.6, MidpointRounding.AwayFromZero); // result:1 Math.Round(0.5, MidpointRounding.AwayFromZero); // result:1 Math.Round(1.5, MidpointRounding.AwayFromZero); // result:2 Math.Round(2.5, MidpointRounding.AwayFromZero); // result:3
保留后倆位小數點要用到另一個重載方法
Math.Round((decimal)22.325, 2,MidpointRounding.AwayFromZero)//result : 22.33
C#實現保留兩位小數的方法
Math.Round(0.333, 2);//按照四舍五入的國際標準
double dbdata = 0.335; string str1 = String.Format("{0:F}", dbdata);//默認為保留兩位
decimal.Round(decimal.Parse("0.3453"), 2)
Convert.ToDecimal("0.3333").ToString("0.00");C#保留小數點后幾位
String.Format("{0:N1}", a) 保留小數點后一位
String.Format("{0:N2}", a) 保留小數點后兩位
String.Format("{0:N3}", a) 保留小數點后三位C#保留小數位N位四舍五入
double s=0.55555; ??
result=s.ToString("#0.00");//點后面幾個0就保留幾位?C#保留小數位N位四舍五入
double dbdata = 0.55555; ??
string str1 = dbdata.ToString("f2");//fN 保留N位,四舍五入總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

