C# Math.Round() 四舍五入 以及 保留两位小数的方法

版权声明:原创图片,自截图片,纯手打文字,经过允许才可转载!业余个人经验分享,有不足的地方请留言,或点【投票】以资鼓励;觉得帮了小忙,请点个赞;还可以点击分享;怕下次出问题之后忘记找不到,可点击收藏。谢谢合作。 https://blog.csdn.net/qq_40985921/article/details/85414484

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# 实现保留两位小数的方法

1、Math.Round(0.333, 2);//按照四舍五入的国际标准
2、double dbdata = 0.335; string str1 = String.Format("{0:F}", dbdata);//默认为保留两位
3、decimal.Round(decimal.Parse(“0.3453”), 2)
4、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位,四舍五入

猜你喜欢

转载自blog.csdn.net/qq_40985921/article/details/85414484