具体代码如下:暂不支持浮点数四舍五入操作
1 static void Main(string[] args) 2 { 3 string numStr = "-177.00"; 4 int num; 5 string isSuccess=IntParse(numStr, out num)?"Yes":"No"; 6 Console.WriteLine($"字符串:{numStr} 是否转换成功:{isSuccess} 转换为整数:{num}"); 7 Console.ReadKey(); 8 } 9 private static bool IntParse(string str,out int res) 10 { 11 Dictionary<string, int> numDic = new Dictionary<string, int> 12 { 13 {"0",0 }, 14 {"1",1 }, 15 {"2",2 }, 16 {"3",3 }, 17 {"4",4 }, 18 {"5",5 }, 19 {"6",6 }, 20 {"7",7 }, 21 {"8",8 }, 22 {"9",9 } 23 }; 24 bool isNegative = false; 25 res = 0; 26 if (!String.IsNullOrEmpty(str)) 27 { 28 //符号位 29 if (str.Contains("-")) 30 { 31 isNegative = true; 32 str = str.Replace("-", ""); 33 } 34 //小数位 35 if (str.Contains(".")) 36 { 37 //暂时先不进行四舍五入 38 str = str.Substring(0, str.IndexOf(".")); 39 } 40 char[] nums = str.ToArray(); 41 try 42 { 43 for (int i = 0; i < nums.Length; i++) 44 { 45 46 int n = numDic[nums[i].ToString()]; 47 if (res != 0) 48 res = res * 10 + n; 49 else 50 res = n; 51 } 52 } 53 catch 54 { 55 return false; 56 } 57 if (isNegative) 58 res=-res; 59 return true; 60 } 61 return false; 62 }
运行结果: