C#四舍五入MidpointRounding.AwayFromZero解析
C#四舍五入MidpointRounding.AwayFromZero
四舍五入 在計算中 經(jīng)常使用到,但是如果使用 Math.Round,只是五舍六入
在Math.Round內(nèi)傳入MidpointRounding.AwayFromZero枚舉,就可以實現(xiàn)四舍五入的效果了,
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#四舍五入以及保留小數(shù)位的方法
C#中的Math.Round()并不是使用的"四舍五入"法。
其實C#的Round函數(shù)都是采用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
保留后倆位小數(shù)點要用到另一個重載方法
Math.Round((decimal)22.325, 2,MidpointRounding.AwayFromZero)//result : 22.33
C#實現(xiàn)保留兩位小數(shù)的方法
Math.Round(0.333, 2);//按照四舍五入的國際標(biāo)準(zhǔn) double dbdata = 0.335; string str1 = String.Format("{0:F}", dbdata);//默認(rèn)為保留兩位 decimal.Round(decimal.Parse("0.3453"), 2) Convert.ToDecimal("0.3333").ToString("0.00");
C#保留小數(shù)點后幾位
String.Format("{0:N1}", a) 保留小數(shù)點后一位 String.Format("{0:N2}", a) 保留小數(shù)點后兩位 String.Format("{0:N3}", a) 保留小數(shù)點后三位
C#保留小數(shù)位N位四舍五入
double s=0.55555; ?? result=s.ToString("#0.00");//點后面幾個0就保留幾位?
C#保留小數(shù)位N位四舍五入
double dbdata = 0.55555; ?? string str1 = dbdata.ToString("f2");//fN 保留N位,四舍五入
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
WPF拖動DataGrid滾動條時內(nèi)容混亂的解決方法
這篇文章主要介紹了WPF拖動DataGrid滾動條時內(nèi)容混亂的解決方法2016-10-10C#連接Oracle數(shù)據(jù)庫使用Oracle.ManagedDataAccess.dll
這篇文章主要介紹了C#使用Oracle.ManagedDataAccess.dll的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11C# 使用Microsoft Edge WebView2的相關(guān)總結(jié)
這篇文章主要介紹了C# 使用Microsoft Edge WebView2的相關(guān)總結(jié),幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-02-02