C#四舍五入的4种方法 C#四舍五入的4种方法

发布时间:2025-12-09 12:06:11 浏览次数:2

C#四舍五入的4种方法

1、使用Math.Round方法处理

   double a = 3.1415926;   //使用四色五入保留2位小数   double b = Math.Round(a,3);   Console.WriteLine(b);   //输出:3.142

2、使用 decimal.Round方法处理

double a = 3.1415926; //使用 decimal.Rounddecimal c = decimal.Round(Convert.ToDecimal(a), 3);Console.WriteLine(c);//输出3.142

3、使用 Format() 方法处理

 double a = 3.1415926;string str1 = String.Format("{0:N2}", a);//保留2位string str2 = String.Format("{0:N3}", a);//保留3位Console.WriteLine(str1);//输出:3.14Console.WriteLine(str2);//输出:3.142

4、使用 ToString() 方法处理

ouble a = 3.1415926;string stra = a.ToString("f4"); string strb = a.ToString("#0.000"); Console.WriteLine(stra);//输出:3.1416 Console.WriteLine(strb);//输出:3.142,小数点后有几个0就保留几位

本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/16584634.html


c 四舍五入
需要做网站?需要网络推广?欢迎咨询客户经理 13272073477