문자열을 숫자로 변환하는 방법(C# 프로그래밍 가이드)

숫자 형식(int, long, double 등)에 있는 Parse 또는 TryParse 메서드를 호출하거나 System.Convert 클래스의 메서드를 사용하여 string을 숫자로 변환합니다.

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는 예외를 throw하지만 TryParsefalse를 반환합니다. Parse 메서드를 호출할 때는 항상 예외 처리를 사용하여 구문 분석 작업이 실패하는 경우 FormatException을 catch해야 합니다.

Parse 또는 TryParse 메서드 호출

ParseTryParse 메서드는 문자열의 시작과 끝에 있는 공백을 무시하지만 다른 모든 문자는 적절한 숫자 형식(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 또는 빈 문자열을 확인할 수 있습니다.

다음 예제에서는 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.
    }
}

다음 예제에서는 선행 숫자(16진수 문자 포함) 및 숫자가 아닌 후행 문자를 포함해야 하는 문자열을 구문 분석하는 한 가지 방법을 보여 줍니다. 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 에서 throw하는 가장 일반적인 두 가지 예외를 catch합니다 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 {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