Console.ReadLine()은 무조건 string 타입으로 반환된다. 원하는 입력값이 int거나 다른 타입의 값이라면 예외처리 기반으로 형변환을 해주는 Parse메서드를 사용해야한다.

finally의 경우 try , catch , finally의 finally 부분이며 에러가 발생 시 catch로 넘어가지만 finally는 try와 catch 어디서든 끝에서 실행이 되는 부분이다.

try에서 val이 int가 아닌 문자열로 나오면 FormatException을 예외로 둔 catch 문으로 넘어가게 된다. 그리고 마지막엔 finally로 넘어간다.

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

namespace CS_Tutorial
{
  internal class Program
  {
    static void Main(string[] args)
    {
      string choice = Console.ReadLine();
      int val;
      try
      {
        val = int.Parse(choice);
        Console.WriteLine(val);
      }
      catch(FormatException)
      {
        Console.WriteLine("잘못된 입력");
      }
      finally {
        Console.WriteLine("끝");
      }
    }
  }
}

int.Parse() : 다른 자료형을 int 자료형으로 변경

long.Parse()

float.Parse()

double.Parse()

ToString(): 숫자를 문자열로 반환

 

ToString 변환 후  int값이 string으로 변환됬는지 확인.

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

namespace CS_Tutorial
{
  internal class Program
  {
    static void Main(string[] args)
    {
      int num = 123;
      string s_num = num.ToString();
      Type type = s_num.GetType();
      Console.WriteLine(s_num);
      Console.WriteLine(type.Name);
    }
  }
}

 

소수점 n번째 제한 표시 ToString("Fn") 또는 #.##

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

namespace CS_Tutorial
{
  internal class Program
  {
    static void Main(string[] args)
    {
      double num = 1.21253;
      string s_num = num.ToString("f2"); //소수점 둘째자리 표시.
      Console.WriteLine(s_num);
    }
  }
}

 

#.##  반올림도 해줌

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

namespace CS_Tutorial
{
  internal class Program
  {
    static void Main(string[] args)
    {
      double num = 1.21253;
      string s_num = num.ToString("#.##"); //소수점 둘째자리 표시.
      Console.WriteLine(s_num);
    }
  }
}

 

 

'언어 > C#' 카테고리의 다른 글

ContentControl/ContentTemplate /ContentPresenter/DataTemplate  (0) 2024.10.23
wpf #mvvm with the stateMachine  (0) 2024.10.05
C# Delegate와 Event  (0) 2024.09.08
TDD(with msdn)  (0) 2024.09.08
mvvm viewmodel base  (0) 2024.03.01

+ Recent posts