C#/winform

천단위 숫자 콤마(,) 표시하기

ㅋㅋ! 2021. 2. 24. 17:41
string str =string.Format("{0:#,###}",2345); // 2345 -> 2,345

 

예)

      private void button3_Click(object sender,EventArgs e)
      {
      int num;
      num = Convert.ToInt32(textBox1.Text); // textBox1에 입력된 내용을 int로 변환후 num에 할당
      string str =string.Format("{0:#,###}", num) //num을 문자열 변환 & 콤마표시 후 str에 할당
	  MessageBox.Show(str); // 문자열 str을 메시지박스로 표시
      }

결과)


위 내용을 참고로, 텍스트 박스에 실시간으로 입력되는 숫자에 콤마를 표시할 수 있다.

 

텍스트박스의 TextChanged 이벤트에 아래 코드를 추가한다.

 private void textBox1_TextChanged(object sender, EventArgs e)
        {
            try //숫자 이외의 문자들 입력시, 발생하는 오류를 방지
            {
                int num;
                string temp = textBox1.Text.Replace(",", ""); //입력되는 텍스트들의 ','를 전부 삭제
                num = Convert.ToInt32(temp);                 // 문자열 temp를 int형으로 변환
                string k = string.Format("{0:#,###}", num); // num을 string으로 변환하면서 천단위 콤마 표시

                textBox1.Text = k;
                textBox1.SelectionStart = textBox1.TextLength; //커서를 항상 맨뒤로
            }
            catch (Exception ex) { }
        }

결과)