当前位置:编程学习 > C#/ASP.NET >>

C#解析任意格式的数字字符串

在.NET中, NumberFormatInfo 类是用来设置数字格式的,有了这个类,我们就可以正确解析任意格式的数字字符串。NumberGroupSeparator 属性用来获取或设置在数值中对小数点左边数字进行分组的字符串。NumberDecimalSeparator 属性获取或设置在数值中用作小数点分隔符的字符串。下面是几个例子,通过运行例子,就可以明白其工作原理了。

C# 代码
//NumberGroupSeparator : 获取或设置在数值中对小数点左边数字进行分组的字符串。
//NumberDecimalSeparator : 获取或设置在数值中用作小数点分隔符的字符串。
String num1 = "123,456,789";
String num2 = "123|456|789";
String num3 = "123.456.789";
String num4 = "123,456.789";
String num5 = "123.456,789";
System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo();
nfi.NumberGroupSeparator = ",";
int x1 = int.Parse(num1, System.Globalization.NumberStyles.AllowThousands, nfi);
nfi.NumberGroupSeparator = "|";
int x2 = int.Parse(num2, System.Globalization.NumberStyles.AllowThousands, nfi);
nfi.NumberGroupSeparator = ".";
int x3 = int.Parse(num3, System.Globalization.NumberStyles.AllowThousands, nfi);
nfi.NumberGroupSeparator = ",";
nfi.NumberDecimalSeparator = ".";
Decimal x4 = Decimal.Parse(num4,nfi);
nfi.NumberGroupSeparator = ".";
nfi.NumberDecimalSeparator = ",";
Decimal x5 = Decimal.Parse(num5, nfi);
Response.Write("<li>" + x1);
Response.Write("<li>" + x2);
Response.Write("<li>" + x3);
Response.Write("<li>" + x4);
Response.Write("<li>" + x5);

 
作者  孟宪会

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,