如何:将字符串转换为数字(C# 编程指南)How to: Convert a String to a Number (C# Programming Guide)

可以调用各种数值类型(intlongdouble 等)中找到的 ParseTryParse 方法或使用 System.Convert 类中的方法将字符串转换为数字。You can convert a string to a number by calling the Parse or TryParse method found on the various numeric types (int, long, double, etc.), or by using methods in the System.Convert class.

如果有字符串,则调用 TryParse 方法(例如,int.TryParse("11", out number))或 Parse 方法(例如,var number = int.Parse("11"))会稍微更加高效且简单。If you have a string, it is slightly more efficient and straightforward to call a TryParse method (for example, int.TryParse("11", out number)) or Parse method (for example, var number = int.Parse("11")). 使用 Convert 方法对于实现 IConvertible 的常规对象更有用。Using a Convert method is more useful for general objects that implement IConvertible.

可以对预期字符串会包含的数值类型(如 System.Int32 类型)使用 ParseTryParse 方法。You can use Parse or TryParse methods on the numeric type you expect the string contains, such as the System.Int32 type. Convert.ToInt32 方法在内部使用 ParseThe Convert.ToInt32 method uses Parse internally. Parse 方法返回转换后的数字;TryParse 方法返回 Boolean 值,该值指示转换是否成功,并以 out 参数形式返回转换后的数字。The Parse method returns the converted number; the TryParse method returns a Boolean value that indicates whether the conversion succeeded, and returns the converted number in an out parameter. 如果字符串的格式无效,则 Parse 会引发异常,而 TryParse 会返回 falseIf the string is not in a valid format, Parse throws an exception, whereas TryParse returns false. 调用 Parse 方法时,应始终使用异常处理来捕获分析操作失败时的 FormatExceptionWhen calling a Parse method, you should always use exception handling to catch a FormatException in the event that the parse operation fails.

调用 Parse 和 TryParse 方法Calling the Parse and TryParse methods

ParseTryParse 方法会忽略字符串开头和末尾的空格,但所有其他字符都必须是组成合适数值类型(intlongulongfloatdecimal 等)的字符。The Parse and TryParse methods ignore white space at the beginning and at the end of the string, but all other characters must be characters that form the appropriate numeric type (int, long, ulong, float, decimal, etc.). 如果组成数字的字符串中有任何空格,都会导致错误。Any white space within the string that forms the number causes an error. 例如,可以使用 decimal.TryParse 分析“10”、“10.3”或“ 10 ”,但不能使用此方法分析从“10X”、“1 0”(注意嵌入的空格)、“10 .3”(注意嵌入的空格)、“10e1”(float.TryParse 在此处适用)等中分析出 10。For example, you can use decimal.TryParse to parse "10", "10.3", or " 10 ", but you cannot use this method to parse 10 from "10X", "1 0" (note the embedded space), "10 .3" (note the embedded space), "10e1" (float.TryParse works here), and so on. 此外,无法成功分析值为 nullString.Empty 的字符串。In addition, a string whose value is null or String.Empty fails to parse successfully. 在尝试通过调用 String.IsNullOrEmpty 方法分析字符串之前,可以检查字符串是否为 Null 或为空。You can check for a null or empty string before attempting to parse it by calling the String.IsNullOrEmpty method.

下面的示例演示了对 ParseTryParse 的成功调用和不成功的调用。The following example demonstrates both successful and unsuccessful calls to Parse and TryParse.

using System;

public 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.

        string inputString = "abc";
        if (Int32.TryParse(inputString, out int numValue))
            Console.WriteLine(inputString);
        else
            Console.WriteLine($"Int32.TryParse could not parse '{inputString}' to an int.");
        // Output: Int32.TryParse could not parse 'abc' to an int.
     }
}

下面的示例演示了一种分析字符串的方法,该字符串应包含前导数字字符(包括十六进制字符)和尾随的非数字字符。The following example illustrates one a approach to parsing a string that is expected to include leading numeric characters (including hexadecimal characters) and trailing non-numeric characters. 在调用 TryParse 方法之前,它从字符串的开头向新字符串分配有效字符。It assigns valid characters from the beginning of a string to a new string before calling the TryParse method. 因为要分析的字符串包含少量字符,所以本示例调用 String.Concat 方法将有效字符分配给新字符串。Because the strings to be parsed contain a small number of characters, the example calls the String.Concat method to assign valid characters to a new string. 对于较大的字符串,可以改用 StringBuilder 类。For a larger string, the StringBuilder class can be used instead.

using System;

public 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
    }
}

调用转换方法Calling the Convert methods

下表列出了 Convert 类中可用于将字符串转换为数字的一些方法。The following table lists some of the methods from the Convert class that you can use to convert a string to a number.

数值类型Numeric Type 方法Method
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。该示例将捕获此方法可能引发的最常见的两个异常:FormatExceptionOverflowExceptionThe following example calls the Convert.ToInt32(String) method to convert an input string to an int. The example catches the two most common exceptions that can be thrown by this method, FormatException and OverflowException. 如果生成的数字可以在不超过 Int32.MaxValue 的情况下递增,则示例将向结果添加 1 并显示输出。If the resulting number can be incremented without exceeding Int32.MaxValue, the example adds 1 to the result and displays the output.

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 {0}", ++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

请参阅See also