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#文档:

https://docs.microsoft.com/zh-cn/dotnet/api/system.midpointrounding?view=net-6.0#system-midpointrounding-awayfromzero

 

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位,四舍五入

 

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程宝库

 c#去除字符串左边的0string str="000101";str=str.TrimStart('0');输出结果:str=“101” c#字符串中含有\0的问题 ...