C#四舍五入MidpointRounding.AwayFromZero解析
c#四舍五入midpointrounding.awayfromzero解析
c#四舍五入midpointrounding.awayfromzero
四舍五入 在計算中 經(jīng)常使用到,但是如果使用 math.round,只是五舍六入
在math.round內(nèi)傳入midpointrounding.awayfromzero枚舉,就可以實(shí)現(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#文檔:
https://docs.microsoft.com/zh-cn/dotnet/api/system.midpointrounding?view=net-6.0#system-midpointrounding-awayfromzero
c#四舍五入以及保留小數(shù)位的方法
c#中的math.round()并不是使用的"四舍五入"法。
其實(shí)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ù)點(diǎn)要用到另一個重載方法
math.round((decimal)22.325, 2,midpointrounding.awayfromzero)//result : 22.33
c#實(shí)現(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ù)點(diǎn)后幾位
string.format("{0:n1}", a) 保留小數(shù)點(diǎn)后一位 string.format("{0:n2}", a) 保留小數(shù)點(diǎn)后兩位 string.format("{0:n3}", a) 保留小數(shù)點(diǎn)后三位
c#保留小數(shù)位n位四舍五入
double s=0.55555; ?? result=s.tostring("#0.00");//點(diǎn)后面幾個0就保留幾位?
c#保留小數(shù)位n位四舍五入
double dbdata = 0.55555; ?? string str1 = dbdata.tostring("f2");//fn 保留n位,四舍五入
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持碩編程。