데이터 다루기 - 형 변환

김유원·2023년 11월 28일
0

데이터 형변환

1. 숫자 -> 숫자

* 변수 앞에 (변환할 형태)를 붙인다.

int iTen = 10;
float fTen;
fTen = (float) iTen;

float fFive = 5.5f;
int iFive;
iFive = (int) fFive;

2. 숫자 -> 문자

* ToString() 활용

int x = 10;
float y = 10.0f;

string xStr = x.ToString();
string yStr = y.ToString();

3. 문자 -> 다른 자료형

1) Convert 클래스

  • To자료형 형태로 변환 가능(ex. ToString, ToInt32, ToDouble 등)
string iStr = "20";
int x = Convert.ToInt32(iStr);

string bStr = "true";
bool b = Conver.ToBoolean(bStr);

2) Parse() 함수

  • Parse 함수는 변환할 수 없는 값이면 에러 발생
x = int.Parse(iStr);
b = bool.Parse(bStr);

3) TryParse() 함수

  • Parse() 함수의 에러 발생을 방지하기 위해 사용
  • bool isInt = int.TryParse(입력값, out 변수명) -> true일 시 '변수명'에 변환된 값 선언됨.
bool isSuccess;
isSuccess = int.TryParse(iStr, out x);
//True 출력

bStr = "testtest";
isSuccess = bool.TryParse(bStr, out b);
//False 출력
profile
개발 공부 블로그

0개의 댓글

관련 채용 정보