?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print
C#에서 Textbox안에 쓰여진 모든 것은 문자로 받아들여집니다.
이 때 문자형으로 받아들여진 숫자를 산술 계산을 위해 숫자로 변환해야 할 일이 자주 발생하죠.

Everything is inputed in Textbox in C#, adapt as strings.
So, it happend very oftenly is change from the string type to int type for mathmatical calculation.

이를 위한 2가지 방법을 찾아 보았습니다.
So, I find 2 kinds of ways.

[1] Convert()

int changed = Convert.ToInt16(string X);


[2] Int16.Parse()
int changed = Int32.Parse(string X);


[1] Convert()
Convert 뒤에 점(.)을 붙이면 변환 가능한 Int형(다른 것도 가능)이 나오며, 그 방법은 아래와 같이
()안에 바꿀 문자열을 넣어 주면 됩니다.
Use the dot(.) after Convert, we can see the type list able to change. (Int and other types), the way to use is write the string variables in () as below.

int changed = Convert.ToInt16(string X);

[2] Int16.Parse()
변환할 Int형의 크기를 입력하고 점(.)을 붙이면 Parse() 메서드 사용이 가능합니다.
Typewrite the Int type size and add the dot(.), we can see the Parse() method on the list.

int changed = Int32.Parse(string X);

[주의사항]
그렇다면 위 둘의 차이점은 사용법 뿐일까요? 아닙니다. Convert는 바꿀 문자열이 Null일 경우를 무시해버리지만, Parse는 Null이 있으면 에러를 뿌려줍니다.
때문에, Parse는 적절한 에러 처리가 가능한 프로그램 코딩이 가능합니다.

[Remark]
What is the difference with Convert() & Parse() ? Just typewriting format ? No !
Convert() ignores when the string is Null. But, Parse() makes a error when it meet the Null.
So, we can pragramming the code prepare the error handling by using Parse().



 int op = 0; // 확인 할 값을 넣을 op 변수 선언
            //// declare the variables op 
 
try
{
op = Int32.Parse(intX.ToString()); //intX가 Null 값인지 확인
                   //// Check the intX is Null or not
}
catch
{
MessageBox.Show(op.ToString() + "Error"); 
        //intX가 Null이면 Error Message
        //// if intX is Null then show Error Message Box
}
finally
{
op = 100;
MessageBox.Show(op.ToString()); 
       // 어쨌든 op에 100을 넣고 값 출력
       // Anyway input the 100 at op and print it 
}
 
MessageBox.Show("Finished");



-------------------------------------------


프로그래밍을 하다보면 상당히 골치아픈 문제가 바로 타입 변환 문제이다. 

예를 들면 문자열로 데이터를 받아서 이것을 정수형으로 바꿔야 한다던지.. 이런 경우를 자주 맞이하게 되는데,

 

C / C++에서는 형변환으로 이 모든걸 해결하기에는 한계가 있었다. 타입을 바꾸는 함수를 만들어줘야하는 경우도 있었고, 애시당초에 타입을 잘 맞춰서 코딩하는 방법밖에는 없었다. 어쩌면 이게 더 맞는 것일지도 모르지만..

 

아무튼 C#에서는 이 골치아픈 문제를 해결해주기 위해 정수 계열 타입 및 부동 소수점 계열 타입에 Parse() 라는 메소드를 추가했다.

Parse() 메소드에 문자열을 넘기면 해당 문자열을 정수 혹은 부동소수점 타입으로 변환시켜준다.

 

다음과 같이 사용하면 된다.

 

int a = int.Parse("12345");

float b = float.Parse("123.45");

 

반대로 숫자 데이터를 문자열로 바꾸는 것도 가능하다. 이는 ToString() 메소드를 통해 가능하다.

다음과 같이 사용하면 된다.

 

int c = 12345;

string d = c.ToString();

 

float e = 123.45;

string f = e.ToString();

 

이 두 메소드를 통해 형변환에 대해 좀 더 편리해진 것을 알 수 있다.

오오오... 좋다......




Dreamy의 코드 스크랩

내가 모으고 내가 보는

List of Articles
번호 분류 제목 날짜 조회 수 추천 수
17 C# SmtpClient로 메일 보내기 - gmail 2013.01.18 12288 0
16 C# C# 자주 쓰는 코드 2012.12.10 11949 0
15 C# How to speed adding items to a ListView? 1 2012.12.12 11809 0
14 C# 사용자 정의 이벤트(event) 예제 2013.08.08 11809 0
13 C# DataGridView 컨트롤 Tutorial 2014.02.19 11640 0
12 C# LDAP Active Directory 계정에서 사진 얻어오기 2013.08.07 11373 0
11 C# C# JSON 파싱(parsing): Newtonsoft 및 System.Text.Json 2021.05.15 10989 0
10 C# Application 클래스 2013.09.25 10151 0
9 C# DateTime.ToString 형식 2012.12.24 10023 0
8 C# 델리게이트와 이벤트(Delegates and Events) 2013.08.14 9995 0
7 C# Quick Sort 함수 2013.04.17 9907 0
6 C# is 와 as 키워드 2012.12.24 9880 0
5 C# Download Files from Web [C#] 2014.09.11 9048 0
4 C# Best way to implement keyboard shortcuts in a Windows Forms application 2015.11.06 6675 0
3 C# How to: Programmatically Add an Entry to Outlook Contacts 2015.05.27 6255 0
목록
Board Pagination ‹ Prev 1 2 3 4 5 Next ›
/ 5

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소

Designed by sketchbooks.co.kr / sketchbook5 board skin

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5