C# 문자열 숫자형식 포맷팅 String.Format ( C# Numberic Formatting )

숫자형식 포맷팅을 이용하면 숫자로 이루어진 문자열을 다양한 형태로 출력 할 수 있습니다.
기본적으로 이 포맷팅은 System. String.Format 매서드에 기반하여 적용됩니다.

형식지정자

종류

예제코드

출력결과

C / c

통화
Currency

Response.Write(string.Format(“{0:C}”, 2.5));

₩3

Response.Write(string.Format(“{0:C}”, -3.5));

-₩4

D / d

10진법
Decimal

Response.Write(string.Format(“{0:D}”, 00035));

35

E / e

과학적지수
Scientific

Response.Write(string.Format(“{0:E}”, 342));

3.420000E+02

F / f

고정 소수점
Fixed-point

Response.Write(string.Format(“{0:F2}”, 35.22));

35.22

Response.Write(string.Format(“{0:F0}”, 35.22));

35

G / g

일반
General

Response.Write(string.Format(“{0:G}”, 123456));

123456

N / n

숫자
Number

Response.Write(string.Format(“{0:N}”, 25000000));

25,000,000.00

P / p

백분율
Percentage

Response.Write(string.Format(“{0:P}”, .21548));

21.55%

Response.Write(string.Format(“{0:P1}”, .112345));

11.2%

X / x

16진법
Hexadecimal

Response.Write(string.Format(“{0:X}”, 250));

FA

Response.Write(string.Format(“{0:X}”, 0xffff));

FFFF

자릿수 고정의 경우 Response.Write(string.Format(“{0:D2}”, 1));   ==>”01″

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// This code example demonstrates the String.Format() method.
// Formatting for this example uses the "en-US" culture.
usingSystem;
classSample
{
    enumColor {Yellow = 1, Blue, Green};
    staticDateTime thisDate = DateTime.Now;
    publicstaticvoidMain()
    {
// Store the output of the String.Format method in a string.
    strings = "";
    Console.Clear();
// Format a negative integer or floating-point number in various ways.
    Console.WriteLine("Standard Numeric Format Specifiers");
    s = String.Format(
        "(C) Currency: . . . . . . . . {0:C}\n"+
        "(D) Decimal:. . . . . . . . . {0:D}\n"+
        "(E) Scientific: . . . . . . . {1:E}\n"+
        "(F) Fixed point:. . . . . . . {1:F}\n"+
        "(G) General:. . . . . . . . . {0:G}\n"+
        "    (default):. . . . . . . . {0} (default = 'G')\n"+
        "(N) Number: . . . . . . . . . {0:N}\n"+
        "(P) Percent:. . . . . . . . . {1:P}\n"+
        "(R) Round-trip: . . . . . . . {1:R}\n"+
        "(X) Hexadecimal:. . . . . . . {0:X}\n",
        -123, -123.45f);
    Console.WriteLine(s);
// Format the current date in various ways.
    Console.WriteLine("Standard DateTime Format Specifiers");
    s = String.Format(
        "(d) Short date: . . . . . . . {0:d}\n"+
        "(D) Long date:. . . . . . . . {0:D}\n"+
        "(t) Short time: . . . . . . . {0:t}\n"+
        "(T) Long time:. . . . . . . . {0:T}\n"+
        "(f) Full date/short time: . . {0:f}\n"+
        "(F) Full date/long time:. . . {0:F}\n"+
        "(g) General date/short time:. {0:g}\n"+
        "(G) General date/long time: . {0:G}\n"+
        "    (default):. . . . . . . . {0} (default = 'G')\n"+
        "(M) Month:. . . . . . . . . . {0:M}\n"+
        "(R) RFC1123:. . . . . . . . . {0:R}\n"+
        "(s) Sortable: . . . . . . . . {0:s}\n"+
        "(u) Universal sortable: . . . {0:u} (invariant)\n"+
        "(U) Universal sortable: . . . {0:U}\n"+
        "(Y) Year: . . . . . . . . . . {0:Y}\n",
        thisDate);
    Console.WriteLine(s);
// Format a Color enumeration value in various ways.
    Console.WriteLine("Standard Enumeration Format Specifiers");
    s = String.Format(
        "(G) General:. . . . . . . . . {0:G}\n"+
        "    (default):. . . . . . . . {0} (default = 'G')\n"+
        "(F) Flags:. . . . . . . . . . {0:F} (flags or integer)\n"+
        "(D) Decimal number: . . . . . {0:D}\n"+
        "(X) Hexadecimal:. . . . . . . {0:X}\n",
        Color.Green);      
    Console.WriteLine(s);
    }
}
/*
This code example produces the following results:
Standard Numeric Format Specifiers
(C) Currency: . . . . . . . . ($123.00)
(D) Decimal:. . . . . . . . . -123
(E) Scientific: . . . . . . . -1.234500E+002
(F) Fixed point:. . . . . . . -123.45
(G) General:. . . . . . . . . -123
    (default):. . . . . . . . -123 (default = 'G')
(N) Number: . . . . . . . . . -123.00
(P) Percent:. . . . . . . . . -12,345.00 %
(R) Round-trip: . . . . . . . -123.45
(X) Hexadecimal:. . . . . . . FFFFFF85
Standard DateTime Format Specifiers
(d) Short date: . . . . . . . 6/26/2004
(D) Long date:. . . . . . . . Saturday, June 26, 2004
(t) Short time: . . . . . . . 8:11 PM
(T) Long time:. . . . . . . . 8:11:04 PM
(f) Full date/short time: . . Saturday, June 26, 2004 8:11 PM
(F) Full date/long time:. . . Saturday, June 26, 2004 8:11:04 PM
(g) General date/short time:. 6/26/2004 8:11 PM
(G) General date/long time: . 6/26/2004 8:11:04 PM
    (default):. . . . . . . . 6/26/2004 8:11:04 PM (default = 'G')
(M) Month:. . . . . . . . . . June 26
(R) RFC1123:. . . . . . . . . Sat, 26 Jun 2004 20:11:04 GMT
(s) Sortable: . . . . . . . . 2004-06-26T20:11:04
(u) Universal sortable: . . . 2004-06-26 20:11:04Z (invariant)
(U) Universal sortable: . . . Sunday, June 27, 2004 3:11:04 AM
(Y) Year: . . . . . . . . . . June, 2004
Standard Enumeration Format Specifiers
(G) General:. . . . . . . . . Green
    (default):. . . . . . . . Green (default = 'G')
(F) Flags:. . . . . . . . . . Green (flags or integer)
(D) Decimal number: . . . . . 3
(X) Hexadecimal:. . . . . . . 00000003
*/

String Format for DateTime [C#]

This example shows how to format DateTime using String.Format method. All formatting can be done also using DateTime.ToString method.

Custom DateTime Formatting

There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).
Following examples demonstrate how are the format specifiers rewritten to the output.
[C#]

// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);
String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone

You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeForma­tInfo.DateSepa­rator and DateTimeForma­tInfo.TimeSepa­rator.
[C#]

// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)

Here are some examples of custom date and time formatting:
[C#]

// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt);            // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"
// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt);    // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"
// two/four digit year
String.Format("{0:MM/dd/yy}", dt);            // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

Standard DateTime Formatting

In DateTimeForma­tInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture.
Following table shows patterns defined in DateTimeForma­tInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.

Specifier DateTimeFormatInfo property Pattern value (for en-US culture)
t ShortTimePattern h:mm tt
d ShortDatePattern M/d/yyyy
T LongTimePattern h:mm:ss tt
D LongDatePattern dddd, MMMM dd, yyyy
f (combination of D and t) dddd, MMMM dd, yyyy h:mm tt
F FullDateTimePattern dddd, MMMM dd, yyyy h:mm:ss tt
g (combination of d and t) M/d/yyyy h:mm tt
G (combination of d and T) M/d/yyyy h:mm:ss tt
mM MonthDayPattern MMMM dd
yY YearMonthPattern MMMM, yyyy
rR RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s SortableDateTi­mePattern yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
u UniversalSorta­bleDateTimePat­tern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
(*) = culture independent

Following examples show usage of standard format specifiers in String.Format method and the resulting output.
[C#]

String.Format("{0:t}", dt);  // "4:05 PM"                         ShortTime
String.Format("{0:d}", dt);  // "3/9/2008"                        ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                      LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2008"          LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2008 4:05 PM"  LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2008 4:05 PM"                ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2008 4:05:07 PM"             ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                        MonthDay
String.Format("{0:y}", dt);  // "March, 2008"                     YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"   RFC1123
String.Format("{0:s}", dt);  // "2008-03-09T16:05:07"             SortableDateTime
String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"            UniversalSortableDateTime

“C# 문자열 숫자형식 포맷팅 String.Format ( C# Numberic Formatting )”의 35개의 댓글

  1. Aw, this was an incredibly nice post. Finding the time and
    actual effort to create a top notch article… but what can I say… I procrastinate a
    whole lot and don’t seem to get nearly anything done.

  2. I simply couldn’t leave your web site before suggesting that I really loved the usual info a person provide
    to your guests? Is going to be back regularly
    to investigate cross-check new posts

  3. I simply want to mention I’m newbie to blogging and seriously savored this blog site. More than likely I’m planning to bookmark your site . You definitely come with outstanding well written articles. Cheers for revealing your web site.

  4. I just want to mention I am new to blogging and site-building and absolutely loved you’re blog. Probably I’m likely to bookmark your blog post . You surely have exceptional writings. Thanks a bunch for sharing with us your web page.

  5. There are definitely a great deal of details like that to consider. That is an excellent point to bring up. I provide the ideas above as general ideas however plainly there are questions like the one you bring up where one of the most essential point will be working in straightforward good faith. I don?t understand if finest practices have emerged around things like that, but I make certain that your job is clearly recognized as a fair game. Both kids as well as ladies really feel the effect of just a moment?s satisfaction, for the remainder of their lives.

  6. I was very pleased to find this web-site. I intended to many thanks for your time for this wonderful read!! I most definitely taking pleasure in every little bit of it as well as I have you bookmarked to have a look at brand-new things you post.

  7. This is the best blog for anyone who needs to find out about this topic. You understand so much its virtually laborious to argue with you (not that I really would need…HaHa). You undoubtedly put a new spin on a topic thats been written about for years. Nice stuff, just nice!

  8. I found your blog website on google and inspect a few of your very early articles. Continue to keep up the excellent run. I simply added up your RSS feed to my MSN Information Reader. Looking for onward to finding out more from you later!?

  9. I uncovered your blog site on google and examine a few of your very early blog posts. Continue to maintain the very good run. I just additional up your RSS feed to my MSN News Reader. Seeking ahead to learning more from you in the future!?

  10. Oh my goodness! an amazing post dude. Thank you Nevertheless I am experiencing issue with ur rss. Don?t know why Unable to register for it. Exists anybody obtaining identical rss issue? Anyone who understands kindly react. Thnkx

  11. Aw, this was a really good message. In suggestion I would love to place in composing similar to this additionally? requiring time and also real initiative to make a very good write-up? yet what can I state? I postpone alot and also never seem to obtain something done.

  12. I?d have to talk to you here. Which is not something I generally do! I take pleasure in reading a message that will certainly make people think. Additionally, thanks for allowing me to comment!

  13. The next time I review a blog, I hope that it does not disappoint me as high as this one. I mean, I recognize it was my choice to check out, however I really thought youd have something interesting to claim. All I hear is a bunch of whimpering about something that you can repair if you werent also busy trying to find attention.

  14. I am typically to blog writing and also i actually appreciate your material. The article has truly peaks my interest. I am going to bookmark your site and keep checking for brand-new information.

  15. An interesting discussion is definitely worth comment. I do believe that you ought to write more about this topic, it might not be a taboo matter but typically people don’t speak about such issues. To the next! Many thanks!!

  16. Place on with this write-up, I absolutely think this web site requires much more consideration. I?ll most likely be once again to review far more, thanks for that information.

  17. Wonderful blog post. I discover something much more difficult on different blogs everyday. It will certainly constantly be boosting to check out material from other writers and also exercise a little something from their store. I?d like to utilize some with the material on my blog site whether you don?t mind. Natually I?ll give you a web link on your internet blog. Thanks for sharing.

댓글 남기기