話說,最近一次系統維護 用JS讀取導入Excel中的實驗數據,出現被自動四舍五入。后來到客戶現場聽客戶反饋 Excel實驗數據要求 奇進偶不進。
關于 奇進偶不進 產生的由來:從統計學的角度,“奇進偶舍”比“四舍五入”要科學,在大量運算時,它使舍入后的結果誤差的均值趨于零,而不是像四舍五入那樣逢五就入,導致結果偏向大數,使得誤差產生積累進而產生系統誤差,“奇進偶舍”使測量結果受到舍入誤差的影響降到最低。
Math下找了下,使用Round 的重載,使用 MidpointRounding.ToEven 就可以實現 奇進偶不進。
// 4 double d = 5.214; double res = Math.Round(d, 2, MidpointRounding.ToEven); Console.WriteLine(res);//5.21 //6 d = 5.216; res = Math.Round(d, 2, MidpointRounding.ToEven); Console.WriteLine(res);//5.22 //5 d = 5.215; res = Math.Round(d, 2, MidpointRounding.ToEven); Console.WriteLine(res);//5.22 d = 5.225; res = Math.Round(d, 2, MidpointRounding.ToEven); Console.WriteLine(res);//5.22 //不止小數點后3位時 d = 0.7865666; res = Math.Round(d, 2, MidpointRounding.ToEven); Console.WriteLine(res);//0.79 d = 0.786; res = Math.Round(d, 2, MidpointRounding.ToEven); Console.WriteLine(res);//0.79 d = 0.785; res = Math.Round(d, 2, MidpointRounding.ToEven); Console.WriteLine(res);//0.78
以上這篇關于C# Math 處理奇進偶不進的實現代碼就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答