Jim Lahman's Blog

Fortitude|Endurance|Faith|Teamwork

  Home  |   Contact  |   Syndication    |   Login
  30 Posts | 0 Stories | 18 Comments | 0 Trackbacks

News

Archives

Links

Social

In C++, one uses the sprintf function to build a formatted string like this:

char szOutput[256];
sprintf(szOutput, "At loop position %d.\n", i);



The C# equivalent is the String.Format method [string.format(string, object)].


TrkCmnRec.szMillOrderNbr = String.Format("MO #{0}", i);

Each placeholder in the string is numeric, so if we want to have a string with three placeholders, we would use {0}, {1}, {2},...{n} as shown in this example:

String sA = "Test string"
int i = 10;
Single f = 45.0
String s = String.Format("String = {0}, int = {1}, Single
= {2}", sA, i, f};

String, numeric and date data types have their own formatting specifiers.


Numeric Format Specifiers
Specifier Description Example C#
c Currency; specify the number of decimal places  $12,345.00 string.Format("Currency: {0:c}", iNbr)
d Whole numbers; specifies the minimum number of digits - zeroes will be used to pad the result  12345 string.Format("Whole: {0:d}", iNbr)
e Scientific notation; specifies the number of decimal places  1.2345e+004 string.Format("Exponential: {0:e}", iNbr)
f Fixed-point; specifies the number of decimal places  12345.00 string.Format("Fixed: {0:f3}", iNbr)
n Fixed-point with comma separators; specifies the number of decimal places  12,345.00 string.Format("Fixed formatted: {0:n3}", iNbr)
p percentage; specifies the number of decimal places  1,234,500.00% string.Format("Percentage: {0:p2}", iNbr)
x Hexadecimal  3039 string.Format("Hexadecimal: {0:x}", iNbr)

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
posted on Monday, April 13, 2009 3:56 PM

Feedback

# re: C# string formatting 12/16/2009 10:41 PM Ranjeesh
Very Helpful. thank you.

# re: C# string formatting 2/10/2012 6:50 AM Alain
Nice, thanks for the concise post and explanation. I've used the C/C++/Delphi formatting for years and have become quite comfortable with it. Since I have to jump between C/C++/Delphi and C# regularly, it would have been nice if the .NET team could've kept the old formatting. I'm sure there are some clever reasons for the change, such as supporting new types, but for 99.9% of purposes the old-style would have worked.

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: