如何将字符串转换为数字 - C#

你可以调用数值类型(string、Parse、TryParse 等)中找到的 int 或 long 方法或使用 double 类中的方法将 System.Convert 转换为数字。

调用 TryParse 方法(例如,int.TryParse("11", out number))或 Parse 方法(例如,var number = int.Parse("11"))会稍微高效和简单一些。 使用 Convert 方法对于实现 IConvertible 的常规对象更有用。

对预期字符串会包含的数值类型(如 Parse 类型)使用 TryParse 或 System.Int32 方法。

Convert.ToInt32 方法在内部使用 Parse。

Parse 方法返回转换后的数字;TryParse 方法返回布尔值,该值指示转换是否成功,并以 out 参数形式返回转换后的数字。 如果字符串的格式无效,则 Parse 会引发异常,但 TryParse 会返回 false。 调用 Parse 方法时,应始终使用异常处理来捕获分析操作失败时的 FormatException。

小窍门

可以使用 AI 帮助 将字符串转换为数字。

调用 Parse 或 TryParse 方法

Parse 和 TryParse 方法会忽略字符串开头和末尾的空格,但所有其他字符都必须是组成合适数值类型(int、long、ulong、float、decimal 等)的字符。 如果组成数字的字符串中有任何空格,都会导致错误。 例如,可以使用 decimal.TryParse 分析“10”、“10.3”或“ 10 ”,但不能使用此方法分析从“10X”、“1 0”(注意嵌入的空格)、“10 .3”(注意嵌入的空格)、“10e1”(float.TryParse 在此处适用)等中分析出 10。 无法成功分析值为 null 或 String.Empty 的字符串。 在尝试通过调用 String.IsNullOrEmpty 方法分析字符串之前,可以检查字符串是否为 Null 或为空。

下面的示例演示了对 Parse 和 TryParse 的成功调用和不成功的调用。

using System;

public static class StringConversion

{

public static void Main()

{

string input = String.Empty;

try

{

int result = Int32.Parse(input);

Console.WriteLine(result);

}

catch (FormatException)

{

Console.WriteLine($"Unable to parse '{input}'");

}

// Output: Unable to parse ''

try

{

int numVal = Int32.Parse("-105");

Console.WriteLine(numVal);

}

catch (FormatException e)

{

Console.WriteLine(e.Message);

}

// Output: -105

if (Int32.TryParse("-105", out int j))

{

Console.WriteLine(j);

}

else

{

Console.WriteLine("String could not be parsed.");

}

// Output: -105

try

{

int m = Int32.Parse("abc");

}

catch (FormatException e)

{

Console.WriteLine(e.Message);

}

// Output: Input string was not in a correct format.

const string inputString = "abc";

if (Int32.TryParse(inputString, out int numValue))

{

Console.WriteLine(numValue);

}

else

{

Console.WriteLine($"Int32.TryParse could not parse '{inputString}' to an int.");

}

// Output: Int32.TryParse could not parse 'abc' to an int.

}

}

下面的示例演示了一种分析字符串的方法,该字符串应包含前导数字字符(包括十六进制字符)和尾随的非数字字符。 在调用 TryParse 方法之前,它从字符串的开头向新字符串分配有效字符。 因为要分析的字符串包含少量字符,所以本示例调用 String.Concat 方法将有效字符分配给新字符串。 对于较大的字符串,可以改用 StringBuilder 类。

using System;

public static class StringConversion

{

public static void Main()

{

var str = " 10FFxxx";

string numericString = string.Empty;

foreach (var c in str)

{

// Check for numeric characters (hex in this case) or leading or trailing spaces.

if ((c >= '0' && c <= '9') || (char.ToUpperInvariant(c) >= 'A' && char.ToUpperInvariant(c) <= 'F') || c == ' ')

{

numericString = string.Concat(numericString, c.ToString());

}

else

{

break;

}

}

if (int.TryParse(numericString, System.Globalization.NumberStyles.HexNumber, null, out int i))

{

Console.WriteLine($"'{str}' --> '{numericString}' --> {i}");

}

// Output: ' 10FFxxx' --> ' 10FF' --> 4351

str = " -10FFXXX";

numericString = "";

foreach (char c in str)

{

// Check for numeric characters (0-9), a negative sign, or leading or trailing spaces.

if ((c >= '0' && c <= '9') || c == ' ' || c == '-')

{

numericString = string.Concat(numericString, c);

}

else

{

break;

}

}

if (int.TryParse(numericString, out int j))

{

Console.WriteLine($"'{str}' --> '{numericString}' --> {j}");

}

// Output: ' -10FFXXX' --> ' -10' --> -10

}

}

调用 Convert 方法

下表列出了 Convert 类中可用于将字符串转换为数字的一些方法。

数值类型

方法

decimal

ToDecimal(String)

float

ToSingle(String)

double

ToDouble(String)

short

ToInt16(String)

int

ToInt32(String)

long

ToInt64(String)

ushort

ToUInt16(String)

uint

ToUInt32(String)

ulong

ToUInt64(String)

下面的示例调用 Convert.ToInt32(String) 方法将输入字符串转换为 int。该示例将捕获由此方法引发的两个最常见异常:FormatException 和 OverflowException。 如果生成的数字可以在不超过 Int32.MaxValue 的情况下递增,则示例将向结果添加 1 并显示输出。

using System;

public class ConvertStringExample1

{

static void Main(string[] args)

{

int numVal = -1;

bool repeat = true;

while (repeat)

{

Console.Write("Enter a number between −2,147,483,648 and +2,147,483,647 (inclusive): ");

string? input = Console.ReadLine();

// ToInt32 can throw FormatException or OverflowException.

try

{

numVal = Convert.ToInt32(input);

if (numVal < Int32.MaxValue)

{

Console.WriteLine($"The new value is {++numVal}");

}

else

{

Console.WriteLine("numVal cannot be incremented beyond its current value");

}

}

catch (FormatException)

{

Console.WriteLine("Input string is not a sequence of digits.");

}

catch (OverflowException)

{

Console.WriteLine("The number cannot fit in an Int32.");

}

Console.Write("Go again? Y/N: ");

string? go = Console.ReadLine();

if (go?.ToUpper() != "Y")

{

repeat = false;

}

}

}

}

// Sample Output:

// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive): 473

// The new value is 474

// Go again? Y/N: y

// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive): 2147483647

// numVal cannot be incremented beyond its current value

// Go again? Y/N: y

// Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive): -1000

// The new value is -999

// Go again? Y/N: n

使用 AI 将字符串转换为数字

可以使用 AI 工具(如 GitHub Copilot)生成 C# 代码,将字符串转换为数字。 可以根据要求自定义提示以使用字符串。

下面是 Copilot Chat 提示示例:

Show me how to parse a string as a number, but don't throw an exception if the input string doesn't represent a number.

在应用 Copilot 之前,请查看 Copilot 的建议。

有关详细信息,请参阅 Copilot 常见问题解答。

另请参阅

Visual Studio 中的 GitHub Copilot

VS Code 中的 GitHub Copilot

[an error occurred while processing the directive]