다음을 통해 공유


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

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)

예제

이 예제에서는 ToInt32(String) 메서드를 호출하여 입력 stringint로 변환합니다. 프로그램은 이 메서드가 throw할 수 있는 두 가지 일반적인 예외, FormatExceptionOverflowException을 catch합니다. 정수 저장소 위치를 오버플로하지 않고 숫자를 증가시킬 수 있는 경우 프로그램에서 결과에 1을 더하여 출력을 인쇄합니다.

static void Main(string[] args)
{
    int numVal = -1;
    bool repeat = true;

    while (repeat == true)
    {
        Console.WriteLine("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);
        }
        catch (FormatException e)
        {
            Console.WriteLine("Input string is not a sequence of digits.");
        }
        catch (OverflowException e)
        {
            Console.WriteLine("The number cannot fit in an Int32.");
        }
        finally
        {
            if (numVal < Int32.MaxValue)
            {
                Console.WriteLine("The new value is {0}", numVal + 1);
            }
            else
            {
                Console.WriteLine("numVal cannot be incremented beyond its current value");
            }
        }
        Console.WriteLine("Go again? Y/N");
        string go = Console.ReadLine();
        if (go == "Y" || go == "y")
        {
            repeat = true;
        }
        else
        {
            repeat = false;
        }
    }
    // Keep the console open in debug mode.
    Console.WriteLine("Press any key to exit.");
    Console.ReadKey();    
}
// 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 
// Press any key to exit.

string을 int로 변환하는 또 다른 방법은 Int32 구조체의 Parse 또는 TryParse 메서드를 사용하는 것입니다. ToUInt32 메서드는 Parse를 내부적으로 사용합니다. 문자열이 올바른 형식이 아닌 경우 Parse는 예외를 throw하는 반면, TryParse는 예외를 throw하지 않고 false를 반환합니다. 다음 예제에서는 ParseTryParse에 대한 호출이 성공하는 경우와 실패하는 경우를 모두 보여 줍니다.

int numVal = Int32.Parse("-105");
Console.WriteLine(numVal);
// Output: -105
// TryParse returns true if the conversion succeeded 
// and stores the result in the specified variable. 
int j;
bool result = Int32.TryParse("-105", out j);
if (true == result)
    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";
int numValue;
bool parsed = Int32.TryParse(inputString, out numValue);

if (!parsed)
    Console.WriteLine("Int32.TryParse could not parse '{0}' to an int.\n", inputString);

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

참고 항목

작업

방법: 문자열이 숫자 값을 나타내는지 확인(C# 프로그래밍 가이드)

참조

형식(C# 프로그래밍 가이드)

기타 리소스

.NET Framework 4 서식 지정 유틸리티