Notice
Recent Posts
Recent Comments
«   2024/09   »
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 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

14. 문자열과 숫자의 변환 본문

초보자를 위한 C# 200제/C# 입문

14. 문자열과 숫자의 변환

빌드이너프 2024. 9. 11. 20:26

문자열을 숫자로 바꾸거나, 숫자를 문자열로 바꾸어야 할 경우가 있다.

 

문자열을 숫자로 바꾸는 방법

1) 숫자 형식(int, float, double 등)에 있는 Parse()나 TryParse() 메소드를 사용하는 것

Parse()와 TryParse() 두 메소드 모두 문자열의 앞뒤에 있는 공백은 무시한다.

다른 모든 문자들은 int, double, decimal 등의 숫자 형식에 맞는 문자들이어야 한다

 

2) Convert 클래스의 메소드를 사용하는 것

 

코드

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A014_StringToNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            string input;
            int value;

            Console.Write("1. int로 변환할 문자열을 입력하세요: ");
            input = Console.ReadLine(); // Console.ReadLine()로 문자열을 입력받아 string input에 저장
            bool result = Int32.TryParse(input, out value); // input을 정수 value로 반환, 성공시 result는 true, 실패시 result는 false

            if (!result)
                Console.WriteLine("'{0}'는 int로 변활될 수 없습니다.\n", input);
            else
                Console.WriteLine("int '{0}'으로 변환되었습니다.\n", value);

            Console.Write("2. double로 변환할 문자열을 입력하세요: ");
            input = Console.ReadLine();
            try
            {
                double m = Double.Parse(input);
                //double m = Convert.ToDouble(input);
                Console.WriteLine("double '{0}'으로 변환되었습니다.\n", m);
            }
            catch (FormatException e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}

 

실행