String Formatting in C#

I couldn’t find a quick reference to .NET string formatting using the String.Format() function, so I created this one (which has also spawned this String Formatting FAQ and strangely enough, this cartoon.

When I started working with the .NET framework, one thing puzzled me. I couldn’t find sprintf(). sprintf() is the C function that takes an output buffer, a format string, and any number of arguments, and builds a string for you. For example:

char szError[256];
sprintf(szError, “Error %d occurred.\n”, nError);

This would write “Error 12 occurred.” into the szError buffer (assuming nError was 12). It’s a basic part of C programming and most C++ programmers still use it though better functionality is available in the STL because sprintf is simple to use and clear. The STL equivalent would be:

str << “Error ” << nError << ” occurred.” << endl;

Or something close to that. It’s type-safe, and more OO than sprintf, but not as easy to read and not as easy to localize.

The .NET framework handles strings very nicely – but it takes some getting used to. The rough equivalent of sprintf in .NET is the static String.Format function, which takes a format string and some arguments, and generates an output string. (This is a nice improvement over sprintf since there’s no chance you’ll overflow the output buffer). For example:

string errorString = String.Format(“Error {0} occurred.”, nError);

Teeming with metadata, the .NET environment doesn’t need the format string to say what type of data you’re formatting, just where you want it. (A common sprintf bug is supplying the wrong data type – there’s no protection from using %s instead of %d and having your program crash when sprintf is called).

The {0} in the string above is replaced with the value of nError, but what if you want to specify the number of digits to use? Or the base (hexadecimal etc)? The framework supports all this, but where it seemed confusing is that it’s not the String.Format function that does the string formatting, but rather the types themselves.

Every object has a method called ToString that returns a string representation of the object. The ToString method can accept a string parameter, which tells the object how to format itself – in the String.Format call, the formatting string is passed after the position, for example, “{0:##}”

The text inside the curly braces is {index[,alignment][:formatString]}. If alignment is positive, the text is right-aligned in a field the given number of spaces; if it’s negative, it’s left-aligned.

Strings

There really isn’t any formatting within a string, beyond it’s alignment. Alignment works for any argument being printed in a String.Format call.

Sample Generates
String.Format(“->{1,10}<-”, “Hello”); -> Hello<-
String.Format(“->{1,-10}<-”, “Hello”); ->Hello <-

Numbers

Basic number formatting specifiers:

Specifier Type Format Output (Passed Double 1.42) Output (Passed Int -12400)
c Currency {0:c} $1.42 -$12,400
d Decimal (Whole number) {0:d} System.FormatException -12400
e Scientific {0:e} 1.420000e+000 -1.240000e+004
f Fixed point {0:f} 1.42 -12400.00
g General {0:g} 1.42 -12400
n Number with commas for thousands {0:n} 1.42 -12,400
r Round trippable {0:r} 1.42 System.FormatException
x Hexadecimal {0:x4} System.FormatException cf90

Custom number formatting:

Specifier Type Example Output (Passed Double 1500.42) Note
0 Zero placeholder {0:00.0000} 1500.4200 Pads with zeroes.
# Digit placeholder {0:(#).##} (1500).42
. Decimal point {0:0.0} 1500.4
, Thousand separator {0:0,0} 1,500 Must be between two zeroes.
,. Number scaling {0:0,.} 2 Comma adjacent to Period scales by 1000.
% Percent {0:0%} 150042% Multiplies by 100, adds % sign.
e Exponent placeholder {0:00e+0} 15e+2 Many exponent formats available.
; Group separator see below

The group separator is especially useful for formatting currency values which require that negative values be enclosed in parentheses. This currency formatting example at the bottom of this document makes it obvious:

Dates

Note that date formatting is especially dependant on the system’s regional settings; the example strings here are from my local locale.

Specifier Type Example (Passed System.DateTime.Now)
d Short date 10/12/2002
D Long date December 10, 2002
t Short time 10:11 PM
T Long time 10:11:29 PM
f Full date & time December 10, 2002 10:11 PM
F Full date & time (long) December 10, 2002 10:11:29 PM
g Default date & time 10/12/2002 10:11 PM
G Default date & time (long) 10/12/2002 10:11:29 PM
M Month day pattern December 10
r RFC1123 date string Tue, 10 Dec 2002 22:11:29 GMT
s Sortable date string 2002-12-10T22:11:29
u Universal sortable, local time 2002-12-10 22:13:50Z
U Universal sortable, GMT December 11, 2002 3:13:50 AM
Y Year month pattern December, 2002

The ‘U’ specifier seems broken; that string certainly isn’t sortable.

Custom date formatting:

Specifier Type Example Example Output
dd Day {0:dd} 10
ddd Day name {0:ddd} Tue
dddd Full day name {0:dddd} Tuesday
f, ff, … Second fractions {0:fff} 932
gg, … Era {0:gg} A.D.
hh 2 digit hour {0:hh} 10
HH 2 digit hour, 24hr format {0:HH} 22
mm Minute 00-59 {0:mm} 38
MM Month 01-12 {0:MM} 12
MMM Month abbreviation {0:MMM} Dec
MMMM Full month name {0:MMMM} December
ss Seconds 00-59 {0:ss} 46
tt AM or PM {0:tt} PM
yy Year, 2 digits {0:yy} 02
yyyy Year {0:yyyy} 2002
zz Timezone offset, 2 digits {0:zz} -05
zzz Full timezone offset {0:zzz} -05:00
: Separator {0:hh:mm:ss} 10:43:20
/ Separator {0:dd/MM/yyyy} 10/12/2002

Enumerations

Specifier Type
g Default (Flag names if available, otherwise decimal)
f Flags always
d Integer always
x Eight digit hex.

Some Useful Examples

String.Format(“{0:$#,##0.00;($#,##0.00);Zero}”, value);

This will output “$1,240.00″ if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string “Zero” if the number is zero.

String.Format(“{0:(###) ###-####}”, 8005551212);

This will output “(800) 555-1212″.

193 Responses to “String Formatting in C#”

  1. stevex » Blog Archive » Different Theme Says:

    [...] In case anyone reads this on the main page instead of in an aggregator.. I’m trying out a different theme. It’s wider, so code snippets don’t wrap. I wanted to make my String Formatting in C# page look good since searching for how to do sprintf type formatting in C# is how most people find this site. [...]

  2. pwalls Says:

    Great resource! This is definitely a handy reference page I’ve added to my favorites. However, I did notice a minor error.

    The following:

    String.Format(“{0:(###) ###-####}”, 18005551212);

    Produces (1800) 555-1212 and not (800) 555-1212.

    Otherwise, great information.

  3. Tim Lewis Says:

    This will output “$1,240.00″ if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string “Zero? if the number is zero.

    Correction:
    String.Format(“{0:$#,##0.00;($#,##0.00);Zero}”, 1243.50); // Outputs “$1,243.50″ not the claimed “$1,240.00″

  4. Max Says:

    I want format String

    string.format(“00-0000″),myhouse);

    my-house?

  5. murugan.g Says:

    Hi Steve,

    Thanks for this wonderful article.

    How can i format date like this “December 08th, 2005″.

  6. Jorge de Cardenas Says:

    Someone asked if 0,1 could be formatted to no,yes on your other page
    http://www.stevex.org/CS/blogs/dottext/articles/158.aspx

    this can be done with formatting using:

    String.Format(“{0:yes;;no}”, value)

    => yes if value == 1
    => no if value == 0

  7. Jeremy Says:

    Was this article ripped off from here:

    http://idunno.org/displayBlog.aspx/2004071401

    ?

    I ask because they are almost identical.

  8. stevex Says:

    Nope.. it looks like they’re just surprisingly coincidentally similar. My original article was posted in 2003, over here:

    http://www.stevex.org/CS/blogs/dottext/articles/158.aspx

    His was posted 2004.

  9. Krise Says:

    Nice howto,
    there is a small error in it though:

    the following :

    Sample Generates
    String.Format(?->{1,10} Hello{1,-10}Hello

  10. Broads Says:

    Steve,

    I have found this blog very usefull but was wondering if you may shed some light on the following.
    I have a shopping basket on my site which should display my total as GBP £x.xx however when using the string.format {0:c} the currency of the hosting server is used. So when I developed and tested my site all looked fine. When I then hosted my site it took, i presume, the localisation of the hosts server and displayed as $x.xx

    To get around this I am now using string.format{0:#.##} which is then prefixed with a physical £ sign.

    Is this the correct way to get over this formating issue or is there a better way.

    Thanks

  11. Philippe Quesnel Says:

    great info ! at last, I always swear at the .NET doc when looking form string formatting info ;-)

    note: the 1st example, right at the top of the article:
    String.Format(?->{1,10} Hello{1,-10}Hello

  12. Philippe Quesnel Says:

    oops, sorry, don’t know what happened to my text in the 1st post !! ??

    here it is again, hopefully complete this time !

    great info ! at last, I always swear at the .NET doc when looking form string formatting info ;-)

    note: the 1st example, right at the top of the article:
    String.Format(?->{1,10} Hello{1,-10}Hello
    String.Format(?->{1,-10}Hello

  13. tom callaghan Says:

    I know there is a way to do this, I just cannot remember the format string. I want to force a sign place holder so that either ‘+’ for positive numbers or ‘-’ for negative numbers will print. For example

    34.2 outputs as +34.2 and -34.2 outputs as -34.2

  14. ddegenaro Says:

    if i have converted from like “1110.20″ to “$1,110.20″ using {0:C}
    how do i convert “$1,110.20″ back to “1110.20″..i tried {0:f} and {0:0.00}
    still doesnt work!

  15. Michael Says:

    I was wondering how you format a phone number to look like: 123.456.7890
    I have tried everything I can think of but no luck.
    Any ideas would be helpful.

    Thanks,

    Michael

  16. Gunnar Olerud Says:

    I’d like to know how to format fixed text fields with a filler that is not a space.
    Example: a text BLG should be in a field with 5 characters and the filler character #, i.e. BLG##. The first part of the format is of course: {0,-5:} but I can’t figure out what the formatstring should be.

    Thanks,
    Gunnar

  17. Bob Bedell Says:

    Just thought I’d add that when formatting value types, calling the value types ToString method is more efficient than passing it to String.Format. You avoid a boxing operation. For example:

    Double testDouble = 19.95;

    String testString1 = String.Format(“{0:C}”, testDouble); // Boxing operation required.

    String testString2 = testDouble.ToString(“C”); // No boxing operation required.

    In the first version, testDouble gets boxed on the managed heap, the new reference type is passed to String.Format, and garbage collection is required.

    In the second version, no boxing occurs, the value type on the stack is used, no garbage collection is required, and your IL code is smaller.

    Thanks for a great page Steve.

    Bob

  18. Sandeep Says:

    How can i print 34 as 00034???

  19. Ramkrishna Says:

    This is some great stuff,was really helpful while i was formatting date strings to display it in various types.

  20. shaik rehaman Says:

    great stuff to see about format funtion

  21. Dave Markle Says:

    Steve –

    THANK YOU so much for publishing this. >>Every

  22. MikeG Says:

    Great guide, and to get around the leading 0 when using “dd”, just convert to int

    Assuming today is April 7th,

    String.Format(“{0:dd}”, DateTime.Now) outputs “07″

    int.Parse(String.Format(“{0:dd}”, DateTime.Now)) outputs “7″

    you can throw .ToString() on the end of that if you require a string :)

  23. Deepak Says:

    This is the best resource I have got untill now , Thank you and good job. I have a question , I am databinding to a textbox with the percentage value. The data which comes from the database has a value, and if I use percentage its multiplying with 100. I donot want my value to multiplied by 100,insted it should give me only the value with the % sign at the end. How do I do that. Thanks and U R response for this would be really appriciated.

  24. Matt Says:

    Anyone know how to do the opposite formatting and REMOVE the currency symbol of a string? I tried just removing the symbol from the format but it did not work.

  25. Oskar Austegard Says:

    Deepak, in order to format something as a percentage WITHOUT having the number multiplied by 100, put a single quote (‘) before the % in the format string.

    E.g. string.Format(“{0:##.00′%”, 1.23)
    will yield the desired 1.23%

  26. Deli Shen Says:

    Is there a way to format the string to fixed length such as sprintf(str,”%15.2f”, myDouble)?
    Thanks!

  27. xill Says:

    Useful!

    Question: How can i make a float display like an int when its a whole number and a float with 2 decimals otherwise:

    5.0 -> 5
    5.5 -> 5.50

  28. George Stylli Says:

    Thanks for this great piece of work!

    Saved loads of time.

    Cheers!

    George

  29. Dan Says:

    How about formatting for thousands, so that if you have a number like

    1500000 and you want to formt it like $1.5M
    or
    37503 and looking for a format like $37.5K

  30. Chemlock Says:

    If you have trouble converting thousand seperated string back to ints

    e.g. int x = int.Parse(“1,345″);

    Which fails nicely. You can use the following

    int x = int.Parse(“1,345″,,System.Globalization.NumberStyles.AllowThousands)

    Which give you an x of 1345.

    Doesn’t answer the previous post but it’s useful to know if you are talking about string conversion

  31. Ian Davis Says:

    When I try and do the following line of code on a console app, I get a blank (vb.net).

    Console.WriteLine(String.Format(“{0:#,###}”, CInt(“0″)))

    How can I tweak this to work? Please email me at dbsmilr@gmail.com. Thanks!

  32. Troubled Says:

    How can I get the Hex representation of a String?

    I want:
    String.Format(“{0:x}”, 16)

    To return the same this as:
    String.Format(“{0:x}”, “16″)

    I don’t know how to use a string as an input parameter, but be treated as an int. Any suggesstions?

    Thanks.

  33. Ken Dourado Says:

    Sorry about the last post – got a new keyboard and it submitted the form by mistake.

    I’m trying to find out how String.Format works from a technical point of view. Does it implicitly call the ToString() method of the object in the parameters passed to it?

    If I had a class and overrode the ToString() method like this:

    public class myClass
    {
    public override ToString()
    {
    // returns a string that I implement differently
    }
    }

    Can I write this:

    String.Format(“Text goes here: {0}”, myClass);

    or do I need to do this?

    String.Format(“Text goes here: {0}”, myClass.ToString());

  34. Steve Says:

    Just a note to add: I was having trouble with inserting dates from ASP into SQL and back out. I am in Australia and I noted it was turning it into the American format, this is just a web.config globalization culture issue.

    Add the Culture=”en-AU” and when I DateTime.Parse it didn’t throw an exception.

  35. KierenH Says:

    [quote]
    Troubled Says:
    June 28th, 2006 at 4:43 pm

    How can I get the Hex representation of a String?

    [/quote]

    string hexValue;
    int myInt;
    if ( int32.TryParse( myString, out myInt ) )
    {
    hexValue = string.Format( “{0:x}”, myInt );
    }

    Basically you want to convert the string to an integer before formatting. The above example will try and parse to an int, if the parse is successful, we format the int. Exceptions are surpressed using TryParse so this should be fairly efficient.

  36. Arsalkhan Says:

    Great job dude keep it up ;)

  37. wagn Says:

    i have:
    double d=12000,00 and i use
    Label1.Text = string.Format(“{0:n}”, double.Parse(Label.Text));

    and i get output -> 12.000,00 ,but i would like
    to have output -> 12.000,0

  38. Elson Says:

    Hi wagn Says,

    Try the following:

    Label1.Text = string.Format(”{0:n:1}”, double.Parse(Label.Text));

    Thanks,
    Elson

  39. Elson Says:

    Hi wagn,

    Try the following too:

    Label1.Text = string.Format(”{0:n1}”, double.Parse(Label.Text));

    Thanks,
    Elson

  40. wagn Says:

    Thanks Elson it works

  41. Paul Kahl Says:

    How would you go about setting up a “missing data” format?

    For instance: I’m outputing a string

    is there a way to do the format so that, if the Item is blank, I put in “No Item”?

  42. mike Says:

    I haven’t done a full apples-to-apples comparison here, but a lot (maybe not all) of this is in the documentation:

    Composite formatting: http://msdn2.microsoft.com/en-us/library/txafckwd.aspx
    Numbers, standard: http://msdn2.microsoft.com/en-us/library/dwhawy9k.aspx
    Numbers, custom: http://msdn2.microsoft.com/en-us/library/0c899ak8.aspx
    Datetime, standard: http://msdn2.microsoft.com/en-us/library/az4se3k1.aspx
    Datetime, custom: http://msdn2.microsoft.com/en-us/library/8kb3ddd4.aspx

  43. Victor Says:

    can you help, I need to format text up to 2 decimal places by default but up to a possible 10 decimal places however without the end zeros if it is more than 2 decimal places.

    eg:
    100 should output to 100.00

    100.000 should output to 100.00

    100.0050 should output to 100.005

  44. Jeannie Says:

    Help!! I have a string that is current data in the form of 100000.00. All I am attempting to do is display the commas. What am I doing wrong.

    CurrentData = string.Format(“{0:#,###.##}”, CurrentData)

    Thanx I’d appreciate any assistance you could offer.

  45. Tom Says:

    Is it possible to format 2 data items with one String.Format?
    e.g.

    double dAlloc = 1.0D;
    double dUnAlloc = 2.0D;
    String Out = String.Format(“Allocated: {0:C} Unallocated {1:C} “, dAlloc, dUnAlloc);

    I get FormatException – where am I going wrong?

    My current code has to be:

    String Out = String.Format(“Allocated: {0:C} “, dAlloc) + String.Format(“Unallocated {0:C}”, dUnAlloc);

    Which seems a step backwards from sprintf,

    However with Bob’s comments about boxing, perhaps it should be:-

    String Out = “Allocated: ” + dAlloc.ToString(“C”) + ” Unallocated: ” + dUnAlloc.ToString(“C”);

    Thanks
    Tom

  46. gowrish.p Says:

    Hi,I need to align the numeric fields as right aligned…for doing calculation and better look.
    Is there any way to align a particular field/column as right/left aligned ?
    Any string formats for that…
    Even I tried the first example {0,10}.It doesnt move after some position.I make the value to 20,100….There is no change in its position…
    Awaiting for the reply…
    Thanks..

  47. James Hancock Says:

    Anyone know how to force this date format:

    yyyy-MM-dd h:mm:ss tt

    (obviously easy)

    But! Have it so that the time is 12 hour clock in North America and 24 hour clock in the US?

    I was hoping to be able to do something like this: yyyy-MM-dd T but it doesn’t work :

  48. Ericson Mar Says:

    I think I found a bug.

    “{0:#0.00}” supposed to yeild 2 decimal places always right?

    This doesn’t work (at lease not with the decimal type). I tried multiple cases and it just doesn’t do anything to the format.

    It’s weird. I tried “{0:#,##0.00}” and it works for ONLY values > 1000. Anything

  49. Mark Says:

    Is there a format that would always remove the first character of a value, and then apply some additional formatting. I have the situation where a number is preceded by an alpha character that determines the format type, but want to apply the new format and ignore the first character in a single format statement.

  50. Riady Says:

    Hi Steve,
    First of all, thank you for the great article.

    I have a question; is there a string formating that will do URL encoding as well?

    & -> %26
    ‘ ‘ -> +

  51. sougata Says:

    I have one number as 1234567890 .
    How to format a number in 1,23,45,67,890 style ?
    Another question, how to format a date in dd/mm/yyyy style ?

  52. Al Says:

    For displaying a formatted Social Security Number, I am using:

    String.Format(“{0:###-##-####}”, “123456789″);

    However, this doesn’t show the numbers separated by hyphens. Instead, it shows, 123456789. Any ideas? Thanks.

  53. jansi rajkumar Says:

    Hi
    I have one problem in storing the string value in the database using C#
    for an example if enters the string with single quotes
    s=My father’s;
    When i try to insert teh s string into database using C# i got a error. how can i store the string with single quotes into the database plz help me

    Regards,
    Jansi

  54. freggel Says:

    Could somebody help me

    I need 2 formats:

    one to display the number without decimals
    100.12121 => 100

    and one up to four decimals
    100.00034 => 100.0003

    Thanks in advance

  55. Denny Says:

    This is in regards to the comment from Jeannie. It’s probably a little late but in case anyone else has this problem I wanted to post my solution. I had a lot of problems getting the commas to display and the String.Format in general. Below is an example of what worked for me (the key to this solution is formatting an integer then populating your string with the result), I hope it helps:

    string strVolume = “”;

    int intVolume = Convert.ToInt32(doc.GetElementValue(“//StockQuotes/Stock/Volume”));
    strVolume = String.Format(“{0:#,###}”, intVolume);

  56. Bob Says:

    Hi Steve,
    Can you or anyone please tell me how to remove begening characters from a string. eg. myapple i want to display only apple
    Thank you

  57. Talha Says:

    Hi,

    I want to ask if there is a conversion implementation from c++ printf format to c# string format. For example i have a string something like this:

    (“number1 = %d number2 = %d”,11 56)

    I need a convertor that will parse this string and reformat it that string.Format can understand and show the string on output as:

    number1 = 11 number2 = 56

    Do you know any conversion function or dll that can make this.

  58. Kimberly Says:

    Thanks for this code snippet.

    String.Format(”{0:$#,##0.00;($#,##0.00);Zero}”, value);

    Can you tell me how I would expand on that and make a negative number display in Red?

    Best regards

  59. sunny Says:

    Nice work stevex. It helps a lot i guess.
    Keep it up.

    I come up string formatting

    string.Format(“{0:0##}”, 23); which al ways display 3 digit number
    rest is filled with 0 s while i was finiding a simple way to do this

    this one helps a lot thanks

  60. Sandy Says:

    How can I construct a format mask that will take either the first N characters or the last N characters from a string or number?

  61. Sanjeewa. K. Says:

    Hi,

    How can we uses Curly brackets (i.e. { }) within a parameterized string.

    e.g. string.format(“{SomeString}=’{0}’”,”Hellow”)

    Out should be expected as “{SomeString}=Hellow”

    can you figure this out?

  62. Eugen M. Says:

    To use curly brackets in the formatting string just double them.

    e.g. string.format(”{{SomeString}}={0}”,”Hellow”)
    will produce: “{SomeString}=Hellow”

  63. Alexis Junchaya Says:

    Hello I am Alexis, I’m a system ingenerian from Peru, I am making a report of sales, and I have a problem with the format o the string in the moment to printing. The problem is the Item 5 tjis value is mayor of million. It’s a problem alignment whith the others Items

    NAME VALUE
    Item 1. 23,776.01
    Item 2. 158.00
    Item 3. 858,789.52
    Item 4. 25.05
    Item 5. 8,528,789.00

    I am workig in vb.net 2003 and I’m using these code.

    Dim varItem1 as double
    Dim varItem2 as double
    Dim varItem3 as double
    Dim varItem4 as double
    Dim varItem5 as double

    varItem1= 23,776.01
    varItem2=158.00
    varItem3=858,789.52
    varItem4=25.05
    varItem5=8,528,789.00 (This is the value with problems with alignment in the moment to print)

    e.WriteColumn(String.Format(“{0,10:N}”, 23,776.01), col1)
    e.WriteColumn(String.Format(“{0,10:N}”, 158.00), col1)
    e.WriteColumn(String.Format(“{0,10:N}”, 858,789.52), col1)
    e.WriteColumn(String.Format(“{0,10:N}”,25.05), col1)
    e.WriteColumn(String.Format(“{0,10:N}”, 8,528,789.00), col1)

    Really, I’m looking for many times in internet but I can not find the solucion in order to align correcctly all the values. Thank for the help. I’ll be waitting for some suggestion in this space or in my e-mail= alexjun378@hotmail.com.

  64. Gaurav Arya Says:

    Hey,
    I need to convert an integer to hundred format string… nut all the options I got in String.format() or num.toString() sre converting it to million format..
    i.e. I need to convert 34000000 to 3,40,00,000.00
    not to 34,000,000.00
    Is there any method….????

  65. Rakesh Says:

    When I use String.Format(“{0:#,##}”, x). If x is 0 then it returns me blank string instead of returning 0. Can anyone guide why this is happening?

  66. Dean Says:

    Rakesh : That is because the # is a digit placeholder. use {0:0,##} or {0:#,#0} depending on the result that you want.

    I have a question: Does anyone know how to trim a string using the Format method. I ask because I am using an ASP.Net GridView control, and the column has a DataFormat string, that takes a format pattern. I have a column with 2048 chars in, but I want to limit it to about 100.

  67. John S. Says:

    Rakesh, try using 0’s instead of #’s

    I’ve also created a printable cheat sheet for .net format strings: http://john-sheehan.com/blog/index.php/net-cheat-sheets/

  68. john whitt Says:

    Comming from a C/C++ background I see no compellling reason why an insane group of programmers came up with a completely different way of handling string conversion with this insane syntax. Microsoft should be shot for this.

  69. eyal Says:

    How can I convert 1200 –> 1.2K?
    1200000 –> 1.2M

  70. khorner Says:

    To answer the questions about formatting string to currency and back to a numeric datatype: you can add the bitmapped values of the Globalization.NumberStyles enumeration.

    Example:
    ‘ format double to currency
    Me.txtMonthPmt.Text = String.Format(“{0:c}”, pmt)

    ‘ parse currency formatted string to double
    Double.Parse(Me.txtMonthPmt.Text, Globalization.NumberStyles.AllowCurrencySymbol + Globalization.NumberStyles.AllowDecimalPoint + Globalization.NumberStyles.AllowThousands)

    ‘ or Double.Parse(Me.txtMonthPmt.Text, 352)

  71. khz Says:

    {0:n;(n);Zero} seems to be broken.

    Displays ‘n’ or ‘(n)’ or ‘Zero’ but does not actually format the number!

  72. Chris Boley Says:

    Gunnar (16th comment), this response is a year late, but if anyone wants to know the answer, use “padleft” or “padright”.

    i.e. “BLG”.PadRight(5, “#”)

  73. Iftikar Says:

    Thanks for all this. I would like to know how to format this
    if I enter “M” then should display “Male” and if “F” then should display “Female”….Plz anyone can help me out

  74. Serge Says:

    > d Decimal (Whole number)

    What is a “Decimal (Whole number)”? Sure sounds non-intuitive.

  75. fooname Says:

    //I have big Double value (988888888888999999)
    double myVal = 988888888888999999;
    //and when I calling
    Console.WriteLine(myVal)
    //I got 9.88888888889E+17
    //but I still need 988888888888999999 showing in GUI

    how with help only of Thread.CurrentThread.CurrentUICulture or Thread.CurrentThread.CurrentCulture fix my problem?
    tnx

  76. Zytan Says:

    I think you missed explaining what the 0 in {0} is for. I just determined that it is the index into the variable list. So, {0} {1} would show the first two in the list (index #0 and #1). I’ll see if I’m right soon enough.

  77. Cindy Says:

    I need to convert a float to string to display to 4 decimal places. This statement works fine unless the float has a value greater then 1000, then it starts rounding to the 3rd decimal place. If the value is greater then 10,000 the rounding goes down to the 2nd decimal place

    float zyx = 1234.4321F;
    string xxx = String.Format(“{0:f4}”, zyx);
    // results in 1234.4320
    string yyy = String.Format(“{0:#.####}”, zyx);
    // results in 1234.432
    string zzz = String.Format(“{0:0.0000}”, zyx);
    // results in 1234.4320
    string nnn = zyx.ToString(“#.####”);
    // results in 1234.432

    Does anyone have suggestion so that there is no rounding?

  78. Anonymous Says:

    So what do google ads G Strings for men have to do with your site Steve? :)

  79. foolsday Says:

    can anyone help me please in csharp, i was vb programmer and shift into csharp,
    my problem is occured when my string variable has a value of “\”

    for example:

    string registryKey = “Software\MITS\DMBS”;

    Error: i got an error “unrecognized escape sequence”

    any suggestion from u guys will be a great for me, thanks!

  80. lola Says:

    I must show a % number , without multiplied for 100, but i try like said upload with an ‘ , and don´t work
    i must format 100% , i put {0:0′%} , and with 100000 obtain 10000000′%
    what i´m doing wrong ??

  81. Robert Says:

    I’ve dsplayed user login info in a gridview and discovered that the LASTLOGINDATE from aspnet_Membership table is stored in GMT. Is there something simple I can use to convert to the client’s timezone? Any hints would be appreciated. If nothing simple, then I’m guessing client-side scripting right?

  82. Robert Says:

    Lola,

    Your format looks good to me.

    Are you formatting for HTML? I know for a fact that the format …0′% will not work in HTML scripting. If you are, then you might want to try this

    text=”"

    All it is reformatting single and double quotes to make it work. Thus, three single-quotes prior to % will work.

  83. Jankrod Says:

    I have a question that is some what related. I have seen lots of articals taking a date and outputing it in a format. But what I want is to know the format that the user specified.

    Ex:
    input: Jan 2007
    output: MMM YYYY

    Does anyone know how I can get the format string for a user specified string date

  84. James Says:

    I can’t get the Month name to appear.
    the following code:
    string dates = string.Format(“{0:MMMM}”,”04″);
    Console.WriteLine(dates);

    should produce the output of “April” but it does not. All I ever get as output is “04″.
    What wrong with it?

    Thanks,

  85. Ryan Montgomery Says:

    For those who need to format currency.

    Using the decimal value 4219.60 as my number from the database for a product.

    {0}
    4219.60

    {0:c}
    $4,219.60

    {0:c2}
    $4,219.60

    {0:c4}
    $4,219.6000

    {0:$#.#}
    $4219.6

    {0:$#,#.#}
    $4,219.6

    {0:#,#.##}
    $4,219.6

    {0:$#,#.#0}
    $4,219.60

    {0:$#,#.00;Call Us;Call Us} (How I show currency – this does not work for other currencies obviously)
    $4,219.60

    I use the .00 to force 2 decimals and the “;Call Us;Call Us” to show the text “Call Us” in place of negative and null values respectively. (Just in case)

    Hope that helps someone.

  86. Rob Volk Says:

    I’ve noticed that when trying to format numbers with commas for thousands with {0:n}, the result ALWAYS includes at least two digits to the right of the decimal (regardless of the datatype – int or double).

    This properly formats an integer with commas for thousands:
    {0:#,0}

  87. BeeKay Says:

    This is a great article, and has been bookmarked for many months.. but I have a question to help me use it.

    In my script I’m using a databinder, thus:

    The date_of_sale renders as “2/1/2007 12:00:00 AM”, but what I need is just the date and not the time. Can anyone help me use “d” in the DataBinder.Eval statement? I’ve tried applying it as the following, but all gave syntax errors

    (overload – takes arguements ‘1′)

    can’t figure out where I’d use string.format or a ToString – any ideas?

  88. Stubby theCat Says:

    Michael Says at February 7th, 2006 at 3:20 am :
    I was wondering how you format a phone number to look like: 123.456.7890

    I know this is a whole year later, but it was fun to try. It may be a hackey answer, but it works:

    string gg = String.Format(“{0:###-###-####}”, 8005551212);
    string gh=gg.Replace(‘-’,’.’);
    Console.WriteLine(“Heres dotted {0}”,gh);

    p.s. Thanks SteveX for this cool website; its helpful.

  89. Manohar Says:

    To answer the questions about formatting string to currency and back to a numeric datatype: you can add the bitmapped values of the Globalization.NumberStyles enumeration.

    Example:
    ‘ format double to currency
    Me.txtMonthPmt.Text = String.Format(”{0:c}”, pmt)

    ‘ parse currency formatted string to double
    Double.Parse(Me.txtMonthPmt.Text, System.Globalization.NumberStyles.Currency)

  90. Zytan Says:

    {0:0,0} does not work for single digit numbers, it prefixes a 0.

  91. Zytan Says:

    Arne told me to use this: {0:#,0} instead, and it works!

  92. Moose Says:

    Great site, too bad Microsoft can not publish useful help. Thanks for the help.

  93. Santosh Says:

    How to format $32,000.00 as 32000 in C# ? can any one gimme an Idea ?

  94. Shankar Says:

    Hey Guys,

    I am giving the solution to convert integer 652 value to Float value 652.00
    Use this code.

    txtBudget.Text= String.Format(“{0:f2}”,Convert.ToDouble(652))

    Out Put will be:
    652.00

  95. Ally Says:

    Hi Guys!

    Require a format string for extracting out just the decimals e.g. 39.76 should give 76 (after the dot). Anyone can shed some light?

  96. HM Says:

    For Sandy (December 28th, 2006 at 3:02 pm):

    Unfortunately, in order to achieve that kind of behavior, you need more than a formatting string.

  97. rekhakrishnan Says:

    Hi

    Will any one help in my case.

    I have a string like GC_I_ ** *** **** and have one more string which is getting the random numbers of 241231212

    Now I need to combine this two like GC_I_ 241231212. Instead of * and need to add the random numbers using formatting. Can any one help me in this case?

  98. ajantha Says:

    how to convert exponents to number without exponent notation

  99. Sohail Mahboob Says:

    Hi All,

    i want to fromat this string “Fri, 06 Jul 2007 15:14:00 EDT”
    into date like 07/06/2007 15:14:00

    Plz help

  100. Dave Says:

    In response to foolsday, you can either double up the backslashes:

    string registryKey = “Software\\MITS\\DMBS”;

    or put @ before the string literal, which I think suppresses escape sequences and is really useful for path strings:

    string registryKey = @“Software\MITS\DMBS”;

    Btw, Thanks for a really useful page Steve!

  101. Umer Says:

    i hav done formating on a phone number like
    (122) 3434-3434

    i want string back like 12234343434
    plz help me

  102. Michael Hall Says:

    You’ve been Kicked”.

  103. Anastasiosyal Says:

    [QUOTE] hav done formating on a phone number like
    (122) 3434-3434

    i want string back like 12234343434
    plz help me
    [/QUOTE]

    Hi Umar, just replace the parenthesis, the space and the dash with String.Empty

    The expression might look something like this:
    Regex.replace(“(122) 3434-3434″, “[\(\) \-]“, String.Empty);

  104. anurag Says:

    I would appreciate if someone can help me with this sort of formatting requirement
    For example, the price 23547.8710000 should display as 23547.871 and 425.00 should display as 425

  105. az Says:

    Sandeep Says:

    March 13th, 2006 at 9:41 am
    How can i print 34 as 00034???

  106. Giannis Says:

    very helpful post surely worth to bookmark

  107. Harry Says:

    I Am trying to set this up so the percentage only holds 2 deimal places. I am currently getting 0.186% , but I want to display 0.19%.

    Benchmark_Variable1 = String.Format(“{0:0.00}%”, Benchmark_Variable1);

    Can you help me out?

  108. Hiren Says:

    this is really amazing……..
    any one can help me to identify………….

    is there any capital letter in a string?
    is there any special symbol [except hypen '-']in a string?

  109. jessi Says:

    how many characters can be passed within a string?

  110. jambunathan Says:

    how to formating 8/25/2007,12:05:03PM into 25-Aug-2007.

  111. wavounet Says:

    if 8/25/2007, 12:05:03PM is a date you can format with “dd-MMM-yyyy”

    example: string date = DateTime.Now.ToString(“dd-MMM-yyyy”)

    else if isn’t a date convert the string

  112. Amit Choudhary Says:

    this site is really helpful to get the diffrent formate for date and numeric value..
    really helpful..
    Thanks to all of you…

  113. Virendra Says:

    I want to display a number in fix 5 digit number using String.Format function. How I can display?
    Ex: 1. I want to show out 00123 for a number 123.
    2. 45123 for a number 45123.
    3. 00032 for a number 32.

  114. Virendra Says:

    I got the solution to show numbers in fix 5 digit with leading zeros.

    int _num1 = 123;
    int _num2 = 45;
    int _num3 = 123456;

    String.Format(“{0:00000}”, _num1); //”00123″
    String.Format(“{0:00000}”, _num2); //”00045″
    String.Format(“{0:00000}”, _num3); //”123456″

    String.Format(“{0:d5}”, _num1); //”00123″
    String.Format(“{0:d5}”, _num2); //”00045″
    String.Format(“{0:d5}”, _num3); //”123456″

    get more idea by clicking here

  115. Gill Bates Says:

    Anyone know a simple way to format the day of the month as 1st,2nd,3rd,4th,5th etc….

    {0:dddd ddd} Gives “Monday 24″ but I want the th on the end as in “Monday 24th”

    Obviously I could code a function to do it, but wondered if it can be done with format specifiers?

  116. Bino Bose Says:

    Thanx for the post. But i’ve one strange doubt. If im using a textbox wherein user enters date in dd/mm/yyyy or mm/dd/yyy format. How can i convert it to specifically mm/dd/yyyy format?
    I know this is quite stupid idea to put a textbox but still, its a requirement!!

    please reply to my mail too
    binobose@yahoo.com

  117. Doug Says:

    Hi – Can string format be used to put in leading zeros – e.g a fixed length of 5 = 00000 and any number can be inserted, so if 1 is returned 00001 is displayed, if 456 is returned 00456 is displayed and if 12345 is returned 123456 is displayed.

    I can do this by using length and substring but is there a way to do it with string.format?

  118. Omar Melendez Says:

    Hi Steve,

    first i want to tell you thank you for this website, i have used it already more than one time , it been of great help for me.
    I have a question regarding if is posible to format a string that could be ‘True’ or ‘False’ to change the value for example if it returns True i want it to output False and viceversa. Can this be done with string formating?

    Thanks in advance!

  119. Ady Says:

    textBox1.Text i introduced alala ‘ 123 ” xyz

    string s=textBox1.Text

    string query= “insert into table values(‘”+s+”‘);”;

    query —–> insert into table values (‘ alala ‘123 ” xyz’);

    i need query= insert into table values(‘ alala \’ 123\” xyz’);

  120. don nielsen Says:

    Mine is similar to others, but a little different. I would like to replace a series of @’s in a string with a number. The number would the same length as the number of @’s, right justified, and zero filled to the left. So if the string contained @@@, I would want them to be replace by 001. If the next string contains @@@@@, I would want them replaced by 00001. Is there a convenient way to do this with the Format function?

    Using c#, I’m left with an ungainly regex replace command.

    Regex regex = new Regex(@”@+”, RegexOptions.None);
    Match match = regex.Match(offile);

    foreach (Segment seg in idxSegments)
    {
    string f =
    regex.Replace(
    offile,
    new String(‘0′, match.Length) + idxSegments.IndexOf(seg).ToString()
    );
    }

    Is there a more convenient String.Format command where I can specify the match.lg value in formatting the number of digits? Or is it a horse a piece. Either way, I would like to know what String.Format solution would be available.

    Thanks for your time and consideration,
    dvn

  121. Michael Lang Says:

    For those of you that wanted to format a part of a string… you can’t with string.Format. however, it is simple to create a regular expression pair to accomplish this.

    For instance to replace an ssn with a masked ssn: “123456789″ to “xxx-xx-6789″

    First you need the expression to parse the portions of the original ssn into logical named parts:
    (?[0-9]{3})(?[0-9]{2})(?[0-9]{4})

    Then the expression to create the mask:
    XXX-XX-${last}

    Now use it in a Regex.Replace method call:

    string theSSN = “123456789″;
    Regex ssnRegex = new Regex(“(?[0-9]{3})(?[0-9]{2})(?[0-9]{4})”);
    string formattedSSN = ssnRegex.Replace(theSSN, “XXX-XX-${last}”);

  122. Saurabh Says:

    I want to display 10.00 as 10 but if value is 10.50 then it should be displayed as 10.5. Plz can any one help me how to format it in C#

  123. hema Says:

    I need this format let me know how i will be able to achieve this using string format
    if i have a number 2342434345.232
    i need output as 345.232 i.e only 3 main digits no matter what is the input number

  124. enrique Says:

    I would show -9.00 and +9.00 (sign included) with ToString() method… How?

  125. Mike Says:

    Many thanks! Been looking for a summery like this for a while! Cheers! :)

  126. Steve B. Says:

    Hi everyone…
    Wonderful e-document, valuabe inputs from everyone…!!! I’ve been using this page for a while now, for all the formatting ideas I needed…
    I am stuck today however. I want to display a string to a fix 5-digits characters. This is not the usual filling-with-leading-zeros: if it’s less than 5 characters, it must display the character as is, but if it’s more than 5 characters, it must only display the 5 first characters.
    I need to do it with string formatting, and not with the String.Remove function for example…
    Does anyone have an idea???

  127. Steve Trefethen Says:

    Great post, I just found this. Thanks!

  128. siva Says:

    How to format $32,000.00 as 32000 in C# ? can any one gimme an Idea ?

  129. Shivraj Says:

    Thanks Steve u have solved my problem

  130. cienio Says:

    Hi
    How to format string “01234″ to “01-234″
    using
    System.Windows.Forms.Binding(“Text”, this.cBindingSource, “ZIP”, true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, ???);
    instead of ‘???’ we should put string format, any idea ???

  131. Senthil Says:

    Hi

    How to display a number into rs format.

    Like

    dim x as integer=1234567

    Response.write(x), i want to display like this format 12,34,567.00

  132. SteveX Compiled » String Formatting in C# at DSharp Says:

    [...] SteveX Compiled » String Formatting in C# [...]

  133. Publius Says:

    Both the format strings for inserting commas in the thousands place are incorrect. Using the number “1″ as input, {0:N} yields “1.000″ and {0:0,0} yields “01″. The correct format string is “{0:#,#}”.

  134. NXavier Says:

    For the regular expression answer above, a tag was left out. Should read something like this:

    Regex ssnRegex = new Regex(“([0-9]{3})([0-9]{2})(?[0-9]{4})”);
    string formattedSSN = ssnRegex.Replace(theSSN, “XXX-XX-${last}”);

    Of course, there are other formatting rules for Social Security Numbers, but this is an excellent example of how regular expressions can help with all kinds of string formatting and pattern searching problems.

    Thanks for the article! Keep ‘em coming.

  135. NXavier Says:

    Oops – the tag syntax is formatted out of the post.

    Okay, so, after the question mark in the last set (for the last four digits of the SSN), add an open angle-bracked (less-than symbol), the word “last”, followed by a close angle-bracket (greater-than symbol).

    Here it is with a “+” in place of the angle brackets: “([0-9]{3})([0-9]{2})(?+last+[0-9]{4})”

    :-)

  136. Vijay Says:

    Great post! Very comprehensive C# string formatting reference.

  137. VBA parameterised string formatting « Latest Misunderstandings Says:

    [...] VBA parameterised string formatting Posted on 2008-01-22 by waldo As far as I’m aware VBA doesn’t provide a decent way to create and use strings with parameters. So I rolled my own using (only the most basic part of) the c# syntax. [...]

  138. IT help south of france Says:

    For displaying a formatted Social Security Number, I am using:

    String.Format(”{0:###-##-####}”, “123456789″);

    However, this doesn’t show the numbers separated by hyphens. Instead, it shows, 123456789. Any ideas? Thanks.

  139. removals to france Says:

    im sure you should do Convert.ToDecimal(var)) before you use the format method

  140. MattS Says:

    How do we write the day of the month like 1st, 2nd, 3rd, 4th etc.

    Can this be done with date formats?

    I’ve seen a couple people post this question on here but didn’t see any replies.

  141. Kaushal Says:

    Hi Steve

    i used {0:#;(#);Zero} seems to be broken.

    to display negative in parenthesis

    it works fine

    my requirement is to show negative number in parenthesis and having red in color.

    can you please help me out.

    Thanks in advance.
    Kaushal

  142. Jamelle Says:

    Ok for any
    String.Format(”{0:###-##-####}”, “123456789″); (FOR SSN)
    or
    String.Format(”{0:(###) ###-####}”, “123456789″); (FOR PHONE)

    your problem is that your inputs are strings!!!!!!! Do this CHANGE IT TO A DOUBLE
    Double rar = Convert.ToDouble(“123456789″);
    String.Format(”{0:(###) ###-####}”, rar )

    NOW IT WORKS!!!!!!

  143. Ben Joyce Says:

    Good article, solutions and comments.

    Managed to muddle together this to give me currency format without the decimal places, or a dash if no value.

    “£#,##0;(£#,##0);-”

    Thanks all.

    Ben

  144. Formatando String - Eduardo Spaki Says:

    [...] http://blog.stevex.net/index.php/string-formatting-in-csharp/ Posted: May 19 2008, 10:39 PM por spoky | com no comments Abaixo de: Programação, [...]

  145. crocodilu Says:

    there was one guy asking the same thing and never got an answer..

    String.Format(”->{1,10} Hello{1,-10}Hello <-

    What does “10″ do ? It should add 5 spaces to “hello”, but it doesnt. Why just 1? Why if you put 1000 instead of 10 you get the same result ?

    I use (“{0, -30:}”, xx) in code for about 3 times and I get 3 different results depending on xxx value, never exactly 30 characters in total (xxx.lenght + spaces = 30).
    Isnt that what that number is supposed to do ?

  146. Jolly Says:

    Please let me know
    if my amount a= $4.565
    and if i do {0:c2} then it gives me o/p $4.57 but i dnt want to round up. i wnat $4.56.
    Please reply urgently.

  147. Tao Designs Weblog » string formatting in c# Says:

    [...] minutes to find a simple listing of common tostring() formats for c#. Thanks to Steve Tibbett for his blog, « Unable to connect to sql server [...]

  148. Ellis Web » Items of Interest: 2006.07.19 Says:

    [...] String Formatting in C# – Nice guide by Steve Tibbett (via the Daily Grind) [...]

  149. Some String Formatting Examples with C# at { null != Steve } Says:

    [...] http://blog.stevex.net/index.php/string-formatting-in-csharp/ [...]

  150. moondaddy Says:

    Pad numbers with zero:
    int num = 2;
    string str = num.ToString(“00″);
    Console.WriteLine(str);
    // returns “02″

  151. Bo Vistisen Says:

    I can see that this thread has been open for years with many good answers and hints.

    I did run into the problem of printing values in nice fixed columns or fixed length in a flat file. I am not sure that Deli Shen for 2 years ago did get any answer on his question:

    >April 20th, 2006 at 7:38 pm
    >Is there a way to format the string to fixed length such as sprintf(str,”%15.2f”, myDouble)?
    >Thanks!

    And yes there are!

    >Zytan sayed in February 28th, 2007 at 8:35 pm
    >I think you missed explaining what the 0 in {0} is for. I just determined that it is the index into the variable >list. So, {0} {1} would show the first two in the list (index #0 and #1). I’ll see if I’m right soon enough.

    And yes the first {0} {1} are the numbers of the argument in the list.
    The next “6″ indicates 6 characters result length right align (-6 left aligned).
    And then the format demanding at least 0.0 for a zero argument.
    And not to forget the simple return new line for the next row of values.
    Keeping the format in a separate string makes the format usable with short notice.

    So we have:

    Double[] myDouble = new Double[] { -40, -30, -10, -5 };
    String Fmt = “{0,6:##0.0} {1,6:##0.0} {2,6:##0.0} {3,6:##0.0}\r\n”;
    String line = String.Format(Fmt1, myDouble[10], myDouble[1], myDouble[2], myDouble[3]);

    Gives:
    ” -40.0 -20.0 -11.0 -5.0″

  152. Jaime Rodriguez Says:

    Hola everyone, I’ve been reading all the reply’s here but i don’t know if my problem apply’s here.

    so i send this string over a socket to an other application

    lblhora.Text = (hr.ToString()+ “: ” + min.ToString() + “: ” + seg.ToString());

    so the format for the time string is HH:MM:SS but is on the 24 time (there no AM or PM)

    my problem is when the client application receives the string i do get it right but i do not know how to separate and transform to integer each section (HH:MM:SS)

    could someone help me please?

  153. spjnm Says:

    How to format ABCD67 to AB-CD-67?

  154. .NET Developer Cheat Sheets : Brendan Enrick's Blog Says:

    [...] String Formatting in C# [...]

  155. Esteban Nyikos Says:

    Hola Jaime Rodriguez,

    No need to manually parse the date, the format string will do it for you. Try this

    DateTime miFecha = DateTime.Now;
    lblhora.Text = string.Format(“{0:hh:mm:ss}”, miFecha);

    If you must use your example data, try this:
    lblhora.Text = string.Format(“{0:00}:{1:00}:{2:00}”, hr, min, seg);

    saludos,
    _E

  156. SEUNG Says:

    i have a record pulled from my database 120.77 but when i publish this on my
    html page it rounds up to 121.00. c#
    how do i still maintain 120.77 pls reply

  157. davidw Says:

    Hello
    One of the things you could do in printf with C++ and MFC, was to specify when printing a floating number:

    -12.123 negative number
    12.123 positive number but leaves a space at the start so the numbers align. Option 1
    +12.123 positive number, forcing it to put in the +. Option 2
    Are options 1 and 2 available.
    David

  158. Time Track « Staying Sane … or tryin’ Says:

    [...] And the link that saved my ass: http://blog.stevex.net/index.php/string-formatting-in-csharp/ [...]

  159. Formating a floating point number | keyongtech Says:

    [...] follow the links you’ll find something about the format > characters for floating point values. http://blog.stevex.net/index.php/str…ing-in-csharp/ is better than the MS docs in my opinion. [...]

  160. why nobody uses String.Format « Bobobobo’s Weblog Says:

    [...] Formatting numbers in C# [...]

  161. Thomas Kumlehn Says:

    The first left/right aligned Hello sample is wrong: a) it uses {1} instead of {0} and the length 10 does not fit the sample output.

  162. Shibin Says:

    Can i format two strings by inserting adequate spaces between them.
    I have two strings like this in each cell of a datagridview.

    10 ABC —-> Ist Row
    1000 DEF —–>2nd Row etc
    100 ABC

    I want to have the texts in the same alignement. Is it possible thru string formatting

  163. Stan Says:

    Been struggling with this for hours now. Does anybody know how to format doubles with something like “##0.###”, where the decimal points of the numbers printed in lines align?

    Eg.

    123.456
    23.45
    3.4
    0.1
    3
    23
    123

  164. Stan Says:

    Shoot! Ofcourse in the above example the numbers don’t line up as intended. One more try, with underscores were spaces are intended.

    123.456
    _23.45
    __3.4
    __0.1
    __3
    _23
    123

    Thanks.

  165. String Formatting in C# « {Programming} & Life Says:

    [...] in .NET Came across a great reference over at “SteveX Compiled” for formatting strings in C#, check it [...]

  166. Doug Moore Says:

    How can I display this as currency?

    donationTotalLabel.Text = reader["Expr1"].ToString() + ” total funds raised to date.”;

    Thanks everyone,
    -doug

  167. defaultCharacter Says:

    Steve,

    Here it is, 2009, and I found your blog entry from 4 years ago… thanks for taking the time to put it up, because it was really helpful to me in my time of need. :)

    -jm

  168. Java - String.Format « Blogging googling Says:

    [...] Referencias:Class MessageFormatApostrophe handling of java.text.MessageFormatString.Format in C# [...]

  169. Andre Says:

    Hi Steve,

    You are my guardian angel.

    I am a beginner with C# and I needed to find a way to insert a couple of variable values like name and e-mail address inside an e-mail message template that should be read from the disk and easy to change by the client without me having to rebuild the solution with every change in the text.

    Thanx.

  170. Nij Says:

    Hi Steve,

    Recommend that you try ‘o’ (little oh) for your round-trip date format; my notes have that it produces output like so:
    2006-09-25T01:59:47.1875000+01:00

    I don’t recall if I tested it, though. (I think it did for C#2)

    Best Regards,
    Nij

  171. arun Says:

    Hi Steve,
    How to pass currency value in numeric textbox with seperators to store in database with money datatype using C# in Winform

  172. Rafi Says:

    Hi,
    I would like to apply the placeholder and decimals string.format({0:#,#.0#####}) its working fine but after the decimal point iam unable to insert the 0(zeros) please any can help on this

  173. Gabe Says:

    Hi Steve,

    Thanks for the blog – all the formatting one wants in one place!

    On reading the various queries from developers, I came across a few that Globalization could resolve the issue.
    e.g. Decimal Point is Comma issue, can be resolved thus:

    double d=1234567890.120;
    Console.WriteLine(string.Format(System.Globalization.CultureInfo.CreateSpecificCulture(“pt”),
    “{0:#,0.00}”, d)); // outputs “1.234.567.890,12″

    where pt is thc culture for Portuguese
    (see http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.createspecificculture.aspx ) for more on Cultures.

    Similarly, where “lakhs” and “crores” are spoken, as in India, the above culture could be replaced by “hi” (Hindi) with the resulting output being “1,23,45,67,890.12″

    However, the true “Picture” (COBOL anyone?) alignment with “#” for columnar display seems to be sadly lacking, when presented with a variety of numbers, as in Stan’s request or 26 Feb 2009. Perhaps there will be a solution in future …

    Cheers

  174. Chris E Says:

    Oops,

    I hit tab and enter, so it posted.

    Let’s say you are formatting a javascript function

    function Foo()
    {
    add = add + {0}
    }

    If you want to ignore the { } for the function just use

    function Foo()
    {{
    add = add + {0}
    }}

    Just thought I’d share.

  175. Chris Says:

    This post is one of my favourites… I always forget all the string format options

  176. Pavel Says:

    Hello everybody!! Can somebody tells how to delete the last symbol from string, please?
    I need something like this
    textBoxMain.Text = string.Format(“{??????}”, int.Parse(textBoxMain.Text));
    what should I write instead of “{??????}”
    Thanks a lot

  177. Chris Says:

    I use the string.Format to add text to it. I have been trying to figure out how to display a single &. I do not want to do a replace(“&”, “&&”) ever time I need to display this. Dose anyone know of a way to make this work???

    Here is my code
    effectiveBonusesLabel.Text = String.Format(@”Bonuses for … {0}”, _selectedGroup.Name.Value);

    the _selectedGroup.Name.Value returns “Group A & B”
    it is displayed to the users as “Bonuses for … Group A _B”

    Please Help

  178. JeffB Says:

    I want to format a hex number in a field 2 wide with a possible leading space.
    So 0xF prints as ” F”.
    I don’t see how to do this
    X:2 gives “0F”

  179. Sam Says:

    i want to format a double to japanese currency. For some reason .. it doesn’t show digits after decimal

    Dim regionInfo As RegionInfo
    Dim culture As CultureInfo
    For Each culture In CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures)
    regionInfo = New RegionInfo(culture.LCID)
    If regionInfo.ISOCurrencySymbol = CurrencyCode Then
    Exit For
    End If
    Next

    Dim i As Double
    i = 123123123.45
    Return (i.ToString(“c”, culture))

    if i change C to N2 it displays decimal , ofcourse it wont display the currency symbol
    Return (i.ToString(“N2″, culture))

  180. zykes Says:

    hi,

    how about formatting date like “1/1/2009″ into “01/01/2009″, how will you do it?

  181. Tux Says:

    How do i format this ? …

    input (1.1.1 as string) => return (1.01.01).

    Thanks.

  182. Rob Says:

    For positive and negative signs (as requested above), try
    string.Format(“{0:+0.00;-0.00}”, 123.45) // => +123.45
    string.Format(“{0:+0.00;-0.00}”, -123.45) // => -123.45
    string.Format(“{0:+0.00;-0.00}”, 0) // => +0

  183. Harry Says:

    Could somebody help me

    I need 2 formats:

    I want to display the phone number with decimals
    1234567890 => 123.456.789

    Please help me.

  184. harry Says:

    hello,

    I need help with formatting phone number in 123.147.1234 format. Any idea?

    thanks
    Harry

  185. shityoucantremember Says:

    zykes: I would not use string formatting for such purposes. You might want to take a look at the ToString method of DateTime instances, which lets you specify a format in three different ways, one of which requires only a format string.

  186. oes tsetnoc Says:

    Thanks for the code, but when i use it the category’s page does show the thumbnail and the whole text of the entrys…

  187. Terry Sprague Says:

    Thanks, this was a big help!!

  188. Alekhya Says:

    Hi it is a great post.
    I need a help,
    I need to display a big number like 3426745 as ‘34,26,745′

    can anyone help me?
    Thank you in Advance.

  189. Alekhya Says:

    Thanks Gabe,

    I found the solution in the same blog above said by Mr.Gabe which i haven’t noticed yesterday

    int temp1=890120
    string.Format(System.Globalization.CultureInfo.CreateSpecificCulture(“hi”), “{0:#,0}”, temp1);

    gives 8,90,120.

    Thank you all.

  190. khalid Says:

    (C# Help needed)
    well guys , sorry to bother after long time but how would u do this
    i have current system date which is = 02-Dec-2009 and time is 10:36
    i want to make a string from system date using the following statement
    String fileNameCreated = “DayLog-” + SomeFunction(NOW, “Some format”) + “-GPRS-STATS.LOG”;

    i need to have “DayLog-2009-12-02-1036-GPRS-STATS.LOG” in fileNameCreated variable !

    any help ? please email to khalidmehmoodawan AT gmail.com as well.

  191. Olly Says:

    Steve,

    I cannot tell you how many times this page has saved my skin. You are a god amongst men

  192. Chidambaram Says:

    Does anyone have the solution to Kaushal(January 30th, 2008 at 11:21 am ) query?

    Is it possible to use the format pattern to set the color?

    Thank you in advance.

  193. Jason Says:

    @Chidambaram, that would have to be handled at the GUI level, not in the formatting of the string. For example:

    int testNumber = -42;
    Label myLabel = new Label();
    myLabel.Text = testNumber.ToString(“#;(#);Zero”);
    myLabel.ForeColor = (testNumber < 0) ? Color.Red : Color.Black;

    Hope this helps.

Leave a Reply

Powered by WP Hashcash