C#保留小数位的方法集合

本文介绍C#中多种处理数值小数位数的方法,包括使用NumberFormatInfo类进行格式化、ToString方法的不同格式指定符实现四舍五入等,适用于不同场景的需求。
?
1
//1.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo();
provider.NumberDecimalDigits =intDecLength; //要设定的小数位数
double strCashAmt=Convert.ToDouble( this .txtCashAmt.Text); //先把控件內的值转成double
  
this .txtCashAmt.Text = strCashAmt.ToString( "N" ,provider); //再利用ToString函数格式化小数位数
  
   
//2.保留N位,四舍五入 .
  
decimal d= decimal .Round( decimal .Parse( "0.55555" ),2);
  
   
//3.保留N位四舍五入
  
Math.Round(0.55555,2)
  
   
//4,保留N位四舍五入
double dbdata = 0.55555;
string str1 = dbdata.ToString( "f2" ); //fN 保留N位,四舍五入
  
   
//5.保留N位四舍五入
  
string result = String.Format( "{0:N2}" , 0.55555); //2位
  
string result = String.Format( "{0:N3}" , 0.55555); //3位
  
   
//6. 保留N位四舍五入 (不错)
  
double s=0.55555;
result=s.ToString( "#0.00" ); //点后面几个0就保留几位
  
   
//C#下如果显示保留小数位数,及百分号的解决方法:
  
//1、用NumberFormatInfo类来解决:
System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo();
  
provider.PercentDecimalDigits = 2; //小数点保留几位数.
provider.PercentPositivePattern = 2; //百分号出现在何处.
double result = ( double )1 / 3; //一定要用double类型.
Response.Write(result.ToString( "P" , provider));
  
//2、用toString方法.:
public string getRate( double hcount, double task)
{
string rValue;
string temp = "" ;
  
if (task == 0)
{
task = 1;
}
  
double db = (hcount / task) * 100;
  
if (hcount >= task)
{
rValue = "100%" ;
}
else
{
rValue = db.ToString( "#0.#0" ) + "%" ;
}
return rValue;
}
  
string str1 = String.Format( "{0:N1}" ,56789); //result: 56,789.0
string str2 = String.Format( "{0:N2}" ,56789); //result: 56,789.00
string str3 = String.Format( "{0:N3}" ,56789); //result: 56,789.000
string str8 = String.Format( "{0:F1}" ,56789); //result: 56789.0
string str9 = String.Format( "{0:F2}" ,56789); //result: 56789.00
string str11 =(56789 / 100.0).ToString( "#.##" ); //result: 567.89
string str12 =(56789 / 100).ToString( "#.##" ); //result: 567

转载于:https://www.cnblogs.com/wifi/articles/2482312.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值