話說,最近一次系統(tǒng)維護(hù) 用JS讀取導(dǎo)入Excel中的實驗數(shù)據(jù),出現(xiàn)被自動四舍五入。后來到客戶現(xiàn)場聽客戶反饋 Excel實驗數(shù)據(jù)要求 奇進(jìn)偶不進(jìn)。
關(guān)于 奇進(jìn)偶不進(jìn) 產(chǎn)生的由來:從統(tǒng)計學(xué)的角度,“奇進(jìn)偶舍”比“四舍五入”要科學(xué),在大量運算時,它使舍入后的結(jié)果誤差的均值趨于零,而不是像四舍五入那樣逢五就入,導(dǎo)致結(jié)果偏向大數(shù),使得誤差產(chǎn)生積累進(jìn)而產(chǎn)生系統(tǒng)誤差,“奇進(jìn)偶舍”使測量結(jié)果受到舍入誤差的影響降到最低。
Math下找了下,使用Round 的重載,使用 MidpointRounding.ToEven 就可以實現(xiàn) 奇進(jìn)偶不進(jìn)。
// 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 //不止小數(shù)點后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
以上這篇關(guān)于C# Math 處理奇進(jìn)偶不進(jìn)的實現(xiàn)代碼就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答
圖片精選