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).
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″.
September 29th, 2005 at 10:45 pm
[...] 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. [...]
October 30th, 2005 at 9:24 pm
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.
November 23rd, 2005 at 10:51 am
Correction:
String.Format(“{0:$#,##0.00;($#,##0.00);Zero}”, 1243.50); // Outputs “$1,243.50″ not the claimed “$1,240.00″
November 25th, 2005 at 2:17 pm
I want format String
string.format(“00-0000″),myhouse);
my-house?
December 8th, 2005 at 9:30 am
Hi Steve,
Thanks for this wonderful article.
How can i format date like this “December 08th, 2005″.
December 16th, 2005 at 11:07 am
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
December 20th, 2005 at 12:17 pm
Was this article ripped off from here:
http://idunno.org/displayBlog.aspx/2004071401
?
I ask because they are almost identical.
December 20th, 2005 at 12:40 pm
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.
December 22nd, 2005 at 5:46 pm
Nice howto,
there is a small error in it though:
the following :
Sample Generates
String.Format(?->{1,10} Hello{1,-10}Hello
January 3rd, 2006 at 5:39 am
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
January 7th, 2006 at 7:20 pm
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
January 7th, 2006 at 8:01 pm
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
January 18th, 2006 at 4:48 pm
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
February 2nd, 2006 at 6:19 pm
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!
February 7th, 2006 at 3:20 am
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
February 16th, 2006 at 6:18 am
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
February 18th, 2006 at 12:48 pm
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
March 13th, 2006 at 9:41 am
How can i print 34 as 00034???
March 16th, 2006 at 9:09 am
This is some great stuff,was really helpful while i was formatting date strings to display it in various types.
March 23rd, 2006 at 5:58 am
great stuff to see about format funtion
March 23rd, 2006 at 12:15 pm
Steve –
THANK YOU so much for publishing this. >>Every
April 7th, 2006 at 3:52 pm
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 :)
April 10th, 2006 at 9:42 am
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.
April 14th, 2006 at 1:40 pm
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.
April 14th, 2006 at 4:35 pm
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%
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!
April 21st, 2006 at 5:57 pm
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
April 24th, 2006 at 10:39 am
Thanks for this great piece of work!
Saved loads of time.
Cheers!
George
May 4th, 2006 at 11:22 am
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
May 11th, 2006 at 9:29 am
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
June 26th, 2006 at 3:25 pm
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!
June 28th, 2006 at 4:43 pm
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.
July 3rd, 2006 at 12:29 pm
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());
July 5th, 2006 at 6:12 am
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.
July 7th, 2006 at 6:35 am
[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.
July 7th, 2006 at 2:51 pm
Great job dude keep it up ;)
July 17th, 2006 at 5:36 am
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
July 17th, 2006 at 12:47 pm
Hi wagn Says,
Try the following:
Label1.Text = string.Format(”{0:n:1}”, double.Parse(Label.Text));
Thanks,
Elson
July 17th, 2006 at 12:52 pm
Hi wagn,
Try the following too:
Label1.Text = string.Format(”{0:n1}”, double.Parse(Label.Text));
Thanks,
Elson
July 18th, 2006 at 3:16 am
Thanks Elson it works
July 18th, 2006 at 6:03 pm
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”?
July 18th, 2006 at 11:30 pm
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
August 7th, 2006 at 11:28 am
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
August 15th, 2006 at 5:14 pm
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.
September 9th, 2006 at 7:23 am
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
September 18th, 2006 at 6:20 am
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..
September 18th, 2006 at 6:39 pm
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 :
October 2nd, 2006 at 2:46 pm
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
October 11th, 2006 at 3:13 pm
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.
October 17th, 2006 at 3:03 am
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
‘ ‘ -> +
October 17th, 2006 at 7:29 am
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 ?
October 22nd, 2006 at 5:03 pm
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.
October 25th, 2006 at 9:46 am
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
October 25th, 2006 at 10:20 am
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
November 6th, 2006 at 11:52 pm
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);
November 19th, 2006 at 5:31 pm
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
November 20th, 2006 at 6:10 am
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.
November 27th, 2006 at 12:30 pm
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
November 30th, 2006 at 10:55 pm
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
December 28th, 2006 at 3:02 pm
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?
January 10th, 2007 at 1:38 am
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?
January 16th, 2007 at 4:52 pm
To use curly brackets in the formatting string just double them.
e.g. string.format(”{{SomeString}}={0}”,”Hellow”)
will produce: “{SomeString}=Hellow”
January 17th, 2007 at 12:53 pm
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.
January 19th, 2007 at 2:37 am
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….????
January 23rd, 2007 at 8:49 am
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?
January 26th, 2007 at 5:31 am
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.
January 26th, 2007 at 4:47 pm
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/
January 31st, 2007 at 9:08 am
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.
February 2nd, 2007 at 12:53 pm
How can I convert 1200 –> 1.2K?
1200000 –> 1.2M
February 6th, 2007 at 11:47 pm
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)
February 7th, 2007 at 6:46 am
{0:n;(n);Zero} seems to be broken.
Displays ‘n’ or ‘(n)’ or ‘Zero’ but does not actually format the number!
February 8th, 2007 at 7:14 pm
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, “#”)
February 14th, 2007 at 1:25 am
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
February 16th, 2007 at 10:02 pm
> d Decimal (Whole number)
What is a “Decimal (Whole number)”? Sure sounds non-intuitive.
February 21st, 2007 at 11:17 am
//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
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.
March 5th, 2007 at 5:37 pm
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?
March 7th, 2007 at 6:20 am
So what do google ads G Strings for men have to do with your site Steve? :)
March 10th, 2007 at 1:38 am
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!
March 12th, 2007 at 9:43 am
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 ??
March 14th, 2007 at 9:24 pm
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?
March 16th, 2007 at 10:31 am
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.
March 26th, 2007 at 12:07 pm
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
April 5th, 2007 at 11:17 am
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,
April 10th, 2007 at 10:51 am
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.
April 18th, 2007 at 10:29 am
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}
April 21st, 2007 at 11:31 pm
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?
April 25th, 2007 at 8:30 pm
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.
May 3rd, 2007 at 1:31 pm
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)
May 6th, 2007 at 6:47 pm
{0:0,0} does not work for single digit numbers, it prefixes a 0.
May 7th, 2007 at 12:25 pm
Arne told me to use this: {0:#,0} instead, and it works!
May 7th, 2007 at 12:27 pm
Great site, too bad Microsoft can not publish useful help. Thanks for the help.
May 23rd, 2007 at 4:58 am
How to format $32,000.00 as 32000 in C# ? can any one gimme an Idea ?
May 31st, 2007 at 6:11 am
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
June 19th, 2007 at 2:05 am
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?
June 22nd, 2007 at 7:00 pm
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.
June 28th, 2007 at 2:12 am
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?
June 29th, 2007 at 2:33 am
how to convert exponents to number without exponent notation
July 10th, 2007 at 6:30 am
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
July 20th, 2007 at 5:30 am
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!
July 25th, 2007 at 5:01 am
i hav done formating on a phone number like
(122) 3434-3434
i want string back like 12234343434
plz help me
July 26th, 2007 at 12:44 pm
You’ve been Kicked”.
July 27th, 2007 at 8:26 am
[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);
August 2nd, 2007 at 9:50 am
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
August 8th, 2007 at 11:30 pm
Sandeep Says:
March 13th, 2006 at 9:41 am
How can i print 34 as 00034???
August 13th, 2007 at 3:31 am
very helpful post surely worth to bookmark
August 14th, 2007 at 6:02 pm
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?
August 18th, 2007 at 12:13 am
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?
August 18th, 2007 at 12:37 am
how many characters can be passed within a string?
August 24th, 2007 at 11:33 pm
how to formating 8/25/2007,12:05:03PM into 25-Aug-2007.
August 27th, 2007 at 4:27 am
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
August 30th, 2007 at 6:42 am
this site is really helpful to get the diffrent formate for date and numeric value..
really helpful..
Thanks to all of you…
September 17th, 2007 at 12:21 am
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.
September 17th, 2007 at 8:26 am
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
September 25th, 2007 at 4:12 pm
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?
September 28th, 2007 at 2:38 am
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
September 28th, 2007 at 10:38 am
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?
October 12th, 2007 at 5:06 pm
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!
October 13th, 2007 at 4:38 pm
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’);
October 16th, 2007 at 10:52 am
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
October 16th, 2007 at 11:15 am
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}”);
October 17th, 2007 at 6:14 am
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#
October 22nd, 2007 at 2:55 am
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
October 30th, 2007 at 1:22 pm
I would show -9.00 and +9.00 (sign included) with ToString() method… How?
November 8th, 2007 at 3:43 am
Many thanks! Been looking for a summery like this for a while! Cheers! :)
November 9th, 2007 at 8:55 am
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???
November 15th, 2007 at 6:21 pm
Great post, I just found this. Thanks!
November 22nd, 2007 at 7:56 pm
How to format $32,000.00 as 32000 in C# ? can any one gimme an Idea ?
November 24th, 2007 at 10:25 am
Thanks Steve u have solved my problem
December 4th, 2007 at 4:39 am
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 ???
December 12th, 2007 at 12:56 am
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
December 17th, 2007 at 6:14 am
[...] SteveX Compiled » String Formatting in C# [...]
December 19th, 2007 at 9:29 am
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:#,#}”.
December 26th, 2007 at 2:58 pm
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.
December 26th, 2007 at 3:08 pm
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})”
:-)
January 14th, 2008 at 4:48 pm
Great post! Very comprehensive C# string formatting reference.
January 22nd, 2008 at 8:59 am
[...] 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. [...]
January 25th, 2008 at 7:05 am
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.
January 29th, 2008 at 12:56 pm
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.
January 30th, 2008 at 11:21 am
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
February 1st, 2008 at 12:13 pm
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!!!!!!
February 4th, 2008 at 11:58 am
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
May 19th, 2008 at 8:51 pm
[...] 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, [...]
June 5th, 2008 at 9:55 am
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 ?
July 29th, 2008 at 5:11 am
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.
July 29th, 2008 at 4:47 pm
[...] 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 [...]
August 14th, 2008 at 9:27 am
[...] String Formatting in C# – Nice guide by Steve Tibbett (via the Daily Grind) [...]
August 20th, 2008 at 8:32 am
[...] http://blog.stevex.net/index.php/string-formatting-in-csharp/ [...]
August 23rd, 2008 at 11:03 am
Pad numbers with zero:
int num = 2;
string str = num.ToString(“00″);
Console.WriteLine(str);
// returns “02″
October 30th, 2008 at 5:11 am
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″
November 10th, 2008 at 9:19 pm
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?
November 25th, 2008 at 10:33 am
How to format ABCD67 to AB-CD-67?
December 1st, 2008 at 9:57 am
[...] String Formatting in C# [...]
December 1st, 2008 at 4:14 pm
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
December 5th, 2008 at 8:58 am
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
December 15th, 2008 at 9:50 am
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
December 15th, 2008 at 5:16 pm
[...] And the link that saved my ass: http://blog.stevex.net/index.php/string-formatting-in-csharp/ [...]
January 18th, 2009 at 12:10 pm
[...] 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. [...]
January 19th, 2009 at 7:37 pm
[...] Formatting numbers in C# [...]
January 23rd, 2009 at 8:03 am
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.
February 24th, 2009 at 9:16 am
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
February 26th, 2009 at 11:25 am
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
February 26th, 2009 at 11:28 am
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.
March 5th, 2009 at 2:13 am
[...] in .NET Came across a great reference over at “SteveX Compiled” for formatting strings in C#, check it [...]
March 6th, 2009 at 6:30 pm
How can I display this as currency?
donationTotalLabel.Text = reader["Expr1"].ToString() + ” total funds raised to date.”;
Thanks everyone,
-doug
March 28th, 2009 at 1:11 pm
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
March 30th, 2009 at 5:34 pm
[...] Referencias:Class MessageFormatApostrophe handling of java.text.MessageFormatString.Format in C# [...]
April 6th, 2009 at 1:45 pm
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.
April 7th, 2009 at 1:28 am
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
April 9th, 2009 at 6:21 am
Hi Steve,
How to pass currency value in numeric textbox with seperators to store in database with money datatype using C# in Winform
April 16th, 2009 at 6:48 am
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
April 30th, 2009 at 2:30 am
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
May 13th, 2009 at 1:46 pm
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.
June 23rd, 2009 at 4:05 am
This post is one of my favourites… I always forget all the string format options
July 2nd, 2009 at 10:20 am
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
July 7th, 2009 at 11:15 am
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
July 10th, 2009 at 2:30 pm
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”
August 4th, 2009 at 2:31 am
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))
August 11th, 2009 at 5:19 am
hi,
how about formatting date like “1/1/2009″ into “01/01/2009″, how will you do it?
August 29th, 2009 at 10:13 pm
How do i format this ? …
input (1.1.1 as string) => return (1.01.01).
Thanks.
September 7th, 2009 at 7:48 am
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
September 24th, 2009 at 9:07 pm
Could somebody help me
I need 2 formats:
I want to display the phone number with decimals
1234567890 => 123.456.789
Please help me.
September 25th, 2009 at 3:04 pm
hello,
I need help with formatting phone number in 123.147.1234 format. Any idea?
thanks
Harry
September 29th, 2009 at 10:04 am
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.
October 1st, 2009 at 10:22 pm
Thanks for the code, but when i use it the category’s page does show the thumbnail and the whole text of the entrys…
October 15th, 2009 at 10:21 am
Thanks, this was a big help!!
November 10th, 2009 at 4:29 am
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.
November 10th, 2009 at 11:42 pm
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.
December 2nd, 2009 at 12:38 am
(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.
January 11th, 2010 at 12:52 pm
Steve,
I cannot tell you how many times this page has saved my skin. You are a god amongst men
January 27th, 2010 at 8:46 am
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.
February 3rd, 2010 at 9:50 am
@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.
March 24th, 2010 at 7:43 am
hi SteveX, great article and great desing.
I have a doubt: How can I use ToString() sintaxis?
I meant, I have a class MyDateFormat based on Ms example for representing this format”DATE (’2010-03-24′)”. and:
MyDateFormat format = new MyDateFormat();
Console.WriteLine(String.Format(format, “{0}”, date));//works fine
but:
Console.WriteLine(date.ToString(format));//doesn´t work
Console.WriteLine(date.ToString(“{0}”, format));//and doesn´t work
How can I fix my code to use .ToString() sintaxis?
Thanks.
———————————————————————————–
public class MyDateFormat : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(string fmt, object arg, IFormatProvider formatProvider)
{
DateTime f = Convert.ToDateTime (arg);
return “DATE (‘” + f.Year + “-” + f.Month + “-” + f.Day + “‘)” ;
}
}
April 6th, 2010 at 3:11 pm
[...] String formatting: http://blog.stevex.net/string-formatting-in-csharp/ [...]
April 9th, 2010 at 4:06 pm
Steve, very useful post, I refer to it all of the time. Thanks much for taking the time to compose it, and to keep it around for all these years.
April 17th, 2010 at 1:35 am
HI friends, i want after decimal point round value
for ex:
12.52 => 12.50
12.53 => 12.55
12.56 => 12.55
12.58 => 12.60
anyone helpme ….
May 6th, 2010 at 2:16 pm
Yes thanks a lot! I keep coming back to it rather than trying to memorize it!
May 19th, 2010 at 5:37 am
string StrVal=string.Format(“{0:c}”, -2575)
Output
($2,575.00)
How to get -$2,575 only please Provide some Solution ASAP
Thanks in Advance
June 2nd, 2010 at 4:35 pm
@Bhramar…
Try this…
string StrVal = string.Format(“{0:$#,0;;#}”, -12056422.7500)
OUTPUT: -$12,056,423
June 15th, 2010 at 8:44 am
Here is a conumdrum for you. In .NET Convert.ToDouble(“(1.75)”) and Double.Parse(“(1.75)”) return an error of string has incorrect format whereas CDbl(“(1.75)”) returns -1.75, which by the way is the expected result.
In an attempt to fully convert to .NET I have changed all code to use Convert.ToDouble believing Micorsoft would not have screwed things up that badly. WRONG!!!
How do I attempt to maintain .NET conversion with .NET Framework code when only legacy VB6 code will work correctly? Who has an answer that will make this work correctly without using CDbl?
June 24th, 2010 at 4:40 am
Thanks for All,
This one works fine for both -Ve and +Ve decimal values
string.Format(“{0:$#,##0.00;-$#,##0.00;Zero}”, Convert.ToDecimal(“123.45″)) – O/P: $123.45
and
string.Format(“{0:$#,##0.00;-$#,##0.00;Zero}”, Convert.ToDecimal(“-123.45″)) – O/P: -$123.45
July 8th, 2010 at 4:56 am
Hi Steve,
I just wanted to say thanks for this post. I find it very useful and refer to it quite often as I can never seem to remember the formats! I have put a link to it on my blog to share the usefulness :) http://usefulaspandcsharp.wordpress.com/2010/02/05/string-formatting-in-c/
Thanks again,
Sarah
August 2nd, 2010 at 4:08 am
There’s a simple way to just show the day as “2″ instead of “02″. Just do string.Format(“{0:d}”, …) instead of “{0:dd}”.
September 6th, 2010 at 3:10 pm
Super article about the string.format…it helped me a lot!!
thank you very much!
September 16th, 2010 at 7:22 am
I have been working with C# for years (and years) now, and I had no idea about some of these formatting shortcuts. This is awesome and you rock for posting it. Thank you!!!
November 4th, 2010 at 4:45 am
Hi, I am running the code below… And it brings back perfect currency format.
Is there a way that instead of it showing R1,000,000.00 it can show R1 000 000,00
I need to replace the commas with spaces, and the dot with a comma.
I have tried val.Replace, but it does not work.
public string FormatToCurrency(string val)
{
//float _fValue = float.Parse(RemoveChars(val));
double _setValue = double.Parse(RemoveChars(val));
//return _fValue.ToString(“C”);
string _sValue = string.Format(“{0:R0,0.00}”, _setValue);
//float _fValue = float.Parse(_sValue);
return _sValue;
}
public string RemoveChars(string val)
{
return val.Replace(” “, “”);
//return val.Replace(“,”, ” “);
//return val.Replace(“.”, “,”);
}
November 23rd, 2010 at 2:18 pm
public string FormatToCurrency(string val)
{
double _setValue = double.Parse(RemoveChars(val));
// you pick up the commas here due to the formatting
string _sValue = string.Format(“{0:R0,0.00}”, _setValue);
// remove the characters here
return RemoveChars(_sValue);
}
public string RemoveChars(string val)
{
// replace your chars here 1st the commas then the period
string _result = val.Replace(“,”,” “).Replace(“.”,”,”)
return _result;
}
March 15th, 2011 at 8:53 am
Hello sir,
i read these blogs while i was searching for , seperator in numeric values.i work on asp.net .but if i write ilke
lblPrice.Text = string.Format(“{0:#,##}”, Convert.ToInt32(lblPrice.Text)); and values inside that label lblPrice is like 2500 then it gives the correct output like 2,500 but if i wrire 120000 then it gives outside like 125,000, which is not required.
i want to convert 120000 to 1,20000 please help me to sort out this problem
March 16th, 2011 at 6:56 am
Hi,
I have to convert the 6570.90 string value in the curreny fomat $6,570.90 in the gridview template field.
i have tried the following code.but its not get reflected.
Text=”
I am getting the input string was not correct format wh when convert the Eval(“camount”) value in to double like Convert.ToDouble(Eval(“camount”)
Please help me for the solution.
Krishna
April 12th, 2011 at 11:51 am
[...] %d or %f (or the others) require that the parameter be of the correct type, or bad things happen This site has a good description of what you can do with string [...]
May 6th, 2011 at 2:54 am
Handy reference. Bookmarked in my “Utility belt” folder :)
June 24th, 2011 at 7:32 am
The best resource for string formatting in c#! Thank you, man! Awsome!
June 29th, 2011 at 9:26 am
Hi Steve,
Thank you for the gr8 article, however I have been facing a problem while displaying Multiline space padded text in textboxes, the text appears properly aligned in the editor, however when displyed in text boxes the alignment goes crazy.
This appears to be a problem with allocating display spaces for a blank charachter and a normal alphabet, i.e. they consume different amount of space while dispay, for eg
ABC DEF
ABC EF
The length of the two strings is same with the differnce that a space accoupies the position of D in the second string, however the E in second string starts much before than it should have.
Please suggest if there is a way to get past through this and make the text appear formatted.
Thanks in advance
September 3rd, 2011 at 4:09 am
Hi, great thread but I am still searching for a simple way to use string.Format() or .ToString() to output a default string when a nullable numeric parameter is null, similar to the null-coalescing operator ?? that i can use elsewhere to return a numeric value by default.
I.e. if I have the following code:
decimal? d;
string s = string.Format(“d={0}”, d);
I want s to be “d=5″ when d.Value equals 5, but I want s to be “d=null” (or any other default string like n/a or something that I define), if the value of d is actually null.
It would be great if I could say:
string s = string.Format(“{0??null”); // or something simple like that
but the compiler doesn’t like that at all, of course.
Of course I know how I can solve it using a helper variable, for example:
var helper = d.HasValue ? d.Value.ToString() : “null”;
string s = string.Format(“{0}”, helper);
or even
string s=string.Format(“{0}”, d.HasValue ? d.Value.ToString() : “null”);
but I am looking for something more direct using the {} format string.
Thanks for any ideas, guys.
September 23rd, 2011 at 5:37 pm
Hi need to validate version like 1.0.0.0 or 1.2.3.4
I need to make sure that user entered the right format, I tried using ([0-9].[0-9].[0-9].[0-9]) for string format, it works for
single digits like above but not for 1.0.17.2
—I tried ([0-99].[0-99].[0-99].[0-99]) but doesnt work. Any suggestions !! please!
Thank you in advance,
Isaac
October 19th, 2011 at 12:21 am
To format floating point value
use string.format(“{0:n2}” dblValue);
here n2=> 2 will display floating point 2 digit
October 25th, 2011 at 11:01 am
How to used the old sprintf (%.10s) which would cut the string to the max specified:
%.10s -> ;hello wor;
No idea, and I’ve looked for a while….
{0,.10}
{0:10.10}
etc… nothing’s working for my need.
Any suggestions ?
November 16th, 2011 at 5:50 am
The cartoon link is down :-(
Do you have a copy?
Just curious…
No I don’t :( — Steve
December 13th, 2011 at 11:14 am
Hey Steve,
I’ve been using this page as a quick reference for years now. Just wanted to say thanks!
December 21st, 2011 at 7:25 pm
[...] list of (all?) the possible ways to format using string.Format() that I can highly recommend here: http://blog.stevex.net/string-formatting-in-csharp/ Tagged as: C#, c-sharp, ciss, format, string, string.format Leave a comment Comments (0) [...]
January 3rd, 2012 at 2:59 pm
Kinda annoying – this:
{0:0,0}
turns a value of
0
into
“00″
March 6th, 2012 at 4:32 pm
In the aboutBox.cs code:
this.labelVersion.Text = String.Format(“Version {0}”,
AssemblyVersion.Substring(0, AssemblyVersion.IndexOf(“.”, AssemblyVersion.IndexOf(“.”) + 1)));
Not pretty, but gets the job done; just use only the first two boxes for your version number under the assembly.
June 19th, 2012 at 10:53 am
To format a string as a percent without rounding, to a specific number of places:
{0:0.000}%
(add or remove zeros as needed, salt to taste.)
June 27th, 2012 at 5:37 pm
Hey,
I am facing this situation, there is a field dateclosed(datetime, null) in sqlserver, the values can be null when updating or inserts, which defaults to 1/1/1900 if the dataset datacolumn datatype is “System.DateTime” when i pass null values, whereas when i change the dataset datacolumn datatype to “System.Data.SqlTypes.SqlDateTime” the following format doesnt work
DataGrid.Columns["DateClosed"].DefaultCellStyle.Format = “MM/dd/yyyy” or {0:d} etc etc, basically i want to show “MM/dd/yyyy” format which doesnt work if i have “System.Data.SqlTypes.SqlDateTime”, but works fine if its “System.DateTime”
how to overcome this scenario….