C#/์ด๊ฒƒ์ด C#์ด๋‹ค

5. Parse์™€ ToString() ๋ฌธ์ž์—ด์„ ์ˆซ์ž๋กœ, ์ˆซ์ž๋ฅผ ๋ฌธ์ž์—ด๋กœ

Rainbow๐ŸŒˆCoder 2022. 2. 7. 12:23
728x90

<๋ฌธ์ž์—ด์„ ์ˆซ์ž๋กœ> Parse!

C#์€ ์ •์ˆ˜๊ณ„์—ด ํ˜•์‹, ๋ถ€๋™ ์†Œ์ˆ˜์  ํ˜•์‹ ๋ชจ๋‘์—๊ฒŒ Parse()๋ผ๋Š” ๋ฉ”์†Œ๋“œ๋ฅผ ๋„ฃ์—ˆ๋‹ค.

์ด ๋ฉ”์†Œ๋“œ์— ์ˆซ์ž๋กœ ๋ณ€ํ™˜ํ•  ๋ฌธ์ž์—ด์„ ๋„˜๊ธฐ๋ฉด ์ˆซ์ž๋กœ ๋ณ€ํ™˜ํ•ด์ค€๋‹ค.

using System;
using System.Text;
using static System.Console;

namespace Hello
{
    class MainApp
    {
        static void Main(string[] args)
        {
            string numbers = "12345";
            string fnumbers = "123.45";
            int a = int.Parse(numbers);
            float b = float.Parse(fnumbers);

            WriteLine(numbers); //12345
            WriteLine(fnumbers); //123.45
            WriteLine(a); //12345
            WriteLine(b);//123.45
        }
    }
}

 

 

<์ˆซ์ž ๋ฐ์ดํ„ฐ ํ˜•์‹์„ ๋ฌธ์ž์—ด๋กœ>

์ •์ˆ˜ ๊ณ„์—ด ๋ฐ์ดํ„ฐ ํ˜•์‹์ด๋‚˜ ๋ถ€๋™ ์†Œ์ˆ˜์  ๋ฐ์ดํ„ฐ ํ˜•์‹์€ ์ž์‹ ์ด ๊ฐ€์ง„ ์ˆซ์ž๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ํ•˜๋„๋ก,

object๋กœ๋ถ€ํ„ฐ ๋ฌผ๋ ค๋ฐ›์€ ToString() ๋ฉ”์†Œ๋“œ๋ฅผ ์žฌ์ •์˜(์˜ค๋ฒ„๋ผ์ด๋“œ)ํ•œ๋‹ค.

์ˆซ์ž ํ˜•์‹ ๋ณ€์ˆ˜์˜ ToString() ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ๋งŒ์œผ๋กœ ์ˆซ์ž๋กœ๋ถ€ํ„ฐ ๋ฌธ์ž์—ด์„ ์–ป์–ด๋‚ผ ์ˆ˜ ์žˆ๋‹ค.

 

using System;
using System.Text;
using static System.Console;

namespace Hello
{
    class MainApp
    {
        static void Main(string[] args)
        {
            string numbers = "12345";
            string fnumbers = "123.45";
            int a = int.Parse(numbers);
            float b = float.Parse(fnumbers);
            int c = 56789;
            string d = c.ToString();
            float e = 567.89f;
            string f = e.ToString();

            WriteLine(numbers); //12345
            WriteLine(fnumbers); //123.45
            WriteLine(a); //12345
            WriteLine(b); //123.45
            WriteLine(c); //56789
            WriteLine(d); //56789
            WriteLine(e); //567.89
            WriteLine(f); //567.89
        }
    }
}

 

์ตœ์ข… ํ…Œ์ŠคํŠธ ์†Œ์Šค ์ฝ”๋“œ

using System;
using System.Text;
using static System.Console;

namespace Hello
{
    class MainApp
    {
        static void Main(string[] args)
        {
            string numbers = "12345";
            string fnumbers = "123.45";
            int a = int.Parse(numbers);
            float b = float.Parse(fnumbers);
            int c = 56789;
            string d = c.ToString();
            float e = 567.89f;
            string f = e.ToString();
            string g = "9999";
            int h = Convert.ToInt32(g);

            WriteLine(numbers); //12345
            WriteLine(fnumbers); //123.45
            WriteLine(a); //12345
            WriteLine(b); //123.45
            WriteLine(c); //56789
            WriteLine(d); //56789
            WriteLine(e); //567.89
            WriteLine(f); //567.89
            WriteLine(g);  //9999
            WriteLine(h);  //9999
        }
    }
}
728x90