分享方式:


如何將字串轉換為數值 (C# 程式設計手冊)

您可以透過呼叫可在數值型別 (intlongdouble 等) 上找到的 ParseTryParse 方法,或透過使用 System.Convert 類別中的方法,將 string 轉換為數字。

呼叫 TryParse 方法 (例如,int.TryParse("11", out number)) 或 Parse 方法 (例如,var number = int.Parse("11")) 相較之下將更有效率且直接。 使用 Convert 方法比實作 IConvertible 的一般物件更有用。

您可以在預期字串包含的數值型別上使用 ParseTryParse 方法,例如 System.Int32 型別。 Convert.ToInt32 方法會在內部使用 ParseParse 方法會傳回轉換的數字;TryParse 方法會傳回布林值,此值指出轉換是否成功,而且會在 out 參數中傳回轉換的數字。 如果字串的格式無效,Parse 會擲回例外狀況,但 TryParse 會傳回 false。 呼叫 Parse 方法時,您必須一律使用例外狀況處理,在剖析作業失敗時捕捉 FormatException

呼叫 Parse 或 TryParse 方法

ParseTryParse 方法會忽略字串開頭和結尾的空格,但所有其他字元必須是來自適當數值型別 (intlongulongfloatdecimal 等) 的字元。 若構成數字的字串內有任何空格,則會造成錯誤。 例如,您可以使用 decimal.TryParse 來剖析 "10"、"10.3" 或 " 10 ",但您無法使用此方法來從 "10X"、"1 0" (注意內嵌的空格)、"10 .3" (注意內嵌的空格)、"10e1" (float.TryParse 在這裡可以運作) 剖析 10 等。 此外,無法成功剖析值為 nullString.Empty 的字串。 您可以透過呼叫 String.IsNullOrEmpty 方法,在嘗試剖析 Null 或空字串之前先進行檢查。

下列範例示範對 ParseTryParse 的成功呼叫與不成功的呼叫。

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。範例會攔截由這個方法所擲回兩種最常見的例外狀況,分別是 FormatExceptionOverflowException。 若產生的數字可在不超過 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 {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