C#中字符串与数值的相互转换

  在C#中,实现数值与字符串的相互转换主要有两种方式。一是利用.NET Framework中System命名空间下的Convert静态类。二是利用各数值类型结构自身提供的ToString/Parse方法。这里主要介绍后者。

  数值转字符串

  在C#中,int,float,double等数值类型都提供了一个ToString方法,将对应实例的数值转换为其等效的字符串表示形式。最简单的使用方式如下。其它数值类型转字符串类型与此类似。

1 int i = 5;
2 string str = i.ToString();

  字符串转数值

  在C#中,利用int,float,double等数值类型的Parse方法,可以方便的将数字的字符串表示形式转换为它的等效的对应数值类型的数字。下面是一个简单的示例。

1 string str = "3.14159";
2 double d = double.Parse(str);

  不同的数值类型,对于参数str的格式要求有少许的差别。转换方式都是类似的。

  下面提供几个字符串与数值互转的方法源码,方便后期使用。

1 using System;
2
3 public class Str_Num
4 {
5 public static bool IsInt(string str)
6 {
7 if (string.IsNullOrEmpty(str))
8 return false;
9
10 if (str == "-")
11 return false;
12
13 if (str.Substring(0, 1) == "-")
14 str = str.Remove(0, 1);
15
16 foreach (char c in str)
17 {
18 if (c < '0' || c > '9')
19 return false;
20 }
21 return true;
22 }
23
24 public static bool IsNumeric(string str)
25 {
26 if (string.IsNullOrEmpty(str))
27 return false;
28 if (str == "." || str == "-" || str == "-.")
29 return false;
30
31 bool hasPoint = false;
32
33 str = str.TrimStart('-');
34
35 foreach (char c in str)
36 {
37 if (c == '.')
38 if (hasPoint)
39 return false;
40 else
41 hasPoint = true;
42
43 if ((c < '0' || c > '9') && c != '.')
44 return false;
45 }
46 return true;
47 }
48
49 public static int? StringToInt(string str)
50 {
51 if (IsInt(str))
52 return Int32.Parse(str);
53
54 return null;
55 }
56
57 public static float? StringToFloat(string str)
58 {
59 if (IsNumeric(str))
60 return float.Parse(str);
61 return null;
62 }
63
64 public static double? StringToDouble(string str)
65 {
66 if (IsNumeric(str))
67 return double.Parse(str);
68 return null;
69 }
70 }

  上述代码提供的字符串转数字的功能在一般情况下是够用了,但是对于科学计数等形式,仍需对其进行改进。


原文地址:https://www.cnblogs.com/hans_gis/p/2018318.html