본문 바로가기
C++ 200제/코딩 IT 정보

C# int 자료형 변환 (TryParse, Convert.ToInt, string 등)

by vicddory 2018. 4. 22.

C# int로 자료형 변환 방법 (TryParse, Convert.ToInt, string 등)


1. TryParse

가장 보편적인 방법은 INT32 형식에 맞춰 TryParse를 하는 것입니다.


1
2
3
4
5
6
7
8
9
10
string intString = "234";
 
int i = 0;
 
if (!Int32.TryParse(intString, out i))
{
   i = -1;
}
 
return i;
cs


2. Nullable 정수와 TryParse

바로 위의 예제에선 형 변환이 정상적으로 이루어지지 않으면 -1을 반환합니다.

그렇지만, -1 자체에 정량적인 의미가 담겨있을 경우 위와 같은 형식은 이용하지 못합니다.


그래서 String을 분석하고 NULL인지 아닌지를 구분하는 형태도 필요합니다.


1
2
3
4
5
6
private int? ConvertStringToInt(string intString)
{
   int i = 0;
 
   return (Int32.TryParse(intString, out i) ? i : (int?)null);
}
cs


3. Convert

기본적으로 예외 처리는 프로그래밍의 기본인데, 이걸 사용하게되면, 조금 복잡해집니다.


그렇지만... 그래도 예외 처리는 당연히 해야죠.


1
2
3
4
5
6
7
8
9
10
11
int i = 0;
try
{
   i = System.Convert.ToInt32(intString);
}
 
catch (FormatException)
{   // String에서 Int로 형변환이 실패한 경우}
 
catch (OverflowException)
{   // 32비트 정수형이 아닌, 64비트의 경우}
cs


int string 변환[C# int 자료형 변환]


4. 기타 등등


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int i = 0;
 
// bool to Int32
bool b = true;
= Convert.ToInt32(b);
 
// byte to Int32
byte bt = 3;
= Convert.ToInt32(bt);
 
// char to Int32
char c = 'A';
= Convert.ToInt32(c);
 
// DateTime to Int32
DateTime dt = DateTime.Now;
= Convert.ToInt32(dt);
 
// Decimal to Int32
decimal d = 25.678m;
= Convert.ToInt32(d);
 
// double to Int32
double db = 0.007234;
= Convert.ToInt32(db);
cs


C# int로 자료형 변환 방법 (TryParse, Convert.ToInt, string 등)

댓글