Formatting Strings - Listing of formatting characters for C# strings
I use string formatting characters often. Yet, for the life of me I simply can't remember
each one! There has been more than one occasion where I need to add
a currency format to a string, only to forget what the stupid code is. Then I have to go and open
a previous project and search for the line of code where I've used it before. Once I see it, it's
painfully obvious and I think "I'm not going to forget it next time!" Guess what? I forget it next
time... and every time after that. Frustrating! Well, to solve this dilemma with my brain I've put
together this page. Now as long as I remember this website I've created, I'm golden!
String format characters
Using a formatter:
lblCurrency.Text = floatingVal.ToString("C");
Formatting Characters:
C or c
Used to format currency. By default, the flag will prefix the local cultural symbol (a dollar sign [$] for U.S. English).
D or d
Used to format decimal numbers. This flag may also specify the minimum number of digits used to pad the value.
E or e
Used for exponential (scienctific) notation.
F or f
Used for fixed-point formatting.
G or g
Stands for general. This character can be used to format a number to fixed or exponential format.
N or n
Used for basic numerical formatting (with commas).
X or x
Used for hexadecimal formatting. If you use an uppercase X, your hex format will also contain uppercase characters.
P or p
Used for percentage formatting.
Output Examples:
(C) Currency: . . . . . . $1,234.57
(D) Decimal:. . . . . . . 12345
(E) Scientific: . . . . . 1.234567E+003
(F) Fixed point:. . . . . 1234.57
(G) General (default):. . 1234.567
(N) Number: . . . . . . . 1,234.57
(P) Percent:. . . . . . . 123,456.70 %
So, there you have them! Some C# escape characters that are sure to make your life easier.
More information
Drop-In Code