데이터 형식 변환

Completed

Tip

자세한 내용은 텍스트 및 이미지 탭을 참조하세요.

C#은 강력한 형식이므로 값을 한 데이터 형식에서 다른 데이터 형식으로 명시적으로 변환해야 하는 경우가 있습니다. 사용자가 숫자를 입력하는 경우에도 항상 텍스트(astring)를 반환하기 때문에 Console.ReadLine() 사용자 입력을 사용할 때 특히 중요합니다.

변환이 중요한 이유

다음과 같은 일반적인 시나리오를 고려합니다.

Console.Write("Enter your age: ");
string ageInput = Console.ReadLine();
int nextYear = ageInput + 1;    // ERROR! Can't add int to string

사용자 입력을 사용하여 수학을 수행하려면 먼저 문자열을 숫자로 변환해야 합니다.

변환 메서드

C#은 데이터 형식 간에 값을 변경하는 메서드를 제공합니다 Convert .

메서드 로 변환 Example 결과
Convert.ToInt32() int Convert.ToInt32("42") 42
Convert.ToDecimal() 십진수 Convert.ToDecimal("19.99") 19.99m
Convert.ToDouble() 더블 Convert.ToDouble("3.14") 3.14
Convert.ToString() 문자열 Convert.ToString(42) "42"

이전 시나리오를 해결하는 방법은 다음과 같습니다.

Console.Write("Enter your age: ");
string ageInput = Console.ReadLine();
int age = Convert.ToInt32(ageInput);
int nextYear = age + 1;
Console.WriteLine($"Next year you'll be {nextYear}");

C# 코드 편집기에서 이 코드를 직접 실행해 볼 수 있습니다.

구문 분석 메서드

문자열을 숫자로 변환하는 또 다른 방법은 메서드를 사용하는 것입니다 Parse .

int age = int.Parse("25");
decimal price = decimal.Parse("19.99");
double average = double.Parse("87.5");

int.Parse() 둘 다 Convert.ToInt32() 비슷한 작업을 수행합니다. 원하는 스타일을 사용합니다.

숫자 형식 간 변환

숫자 형식(예 decimalint: 숫자 형식) 간에 변환하려면 대상 형식을 괄호 안에 배치하여 캐스트 를 사용합니다.

decimal price = 19.99m;
int wholePrice = (int)price;         // Casts to int: 19 (decimal dropped)
Console.WriteLine(wholePrice);       // Output: 19

분할하는 동안 소수 자릿수를 유지하도록 캐스팅할 수도 있습니다.

int first = 7;
int second = 2;
decimal result = (decimal)first / (decimal)second;
Console.WriteLine(result);           // Output: 3.5

잘못된 변환은 어떻게 되나요?

숫자로 해석할 수 없는 값을 변환하려고 하면 C#에서 오류가 발생합니다.

int number = Convert.ToInt32("hello");    // ERROR: Input string was not in a correct format

지금은 시도하기 전에 값을 변환할 수 있는지 확인합니다. 나중에 오류를 정상적으로 처리하는 방법을 알아봅니다.