String Formatting in C#
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″.
150 Responses to “String Formatting in C#”
1. stevex » Blog Archive » Different Theme Says:
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. [...]
2. pwalls Says:
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.
3. Tim Lewis Says:
November 23rd, 2005 at 10:51 am
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:
November 25th, 2005 at 2:17 pm
I want format String
string.format(”00-0000″),myhouse);
my-house?
5. murugan.g Says:
December 8th, 2005 at 9:30 am
Hi Steve,
Thanks for this wonderful article.
How can i format date like this “December 08th, 2005″.
6. Jorge de Cardenas Says:
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
7. Jeremy Says:
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.
8. stevex Says:
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.
9. Krise Says:
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
10. Broads Says:
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
11. Philippe Quesnel Says:
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
12. Philippe Quesnel Says:
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
13. tom callaghan Says:
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
14. ddegenaro Says:
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!
15. Michael Says:
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
16. Gunnar Olerud Says:
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
17. Bob Bedell Says:
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
18. Sandeep Says:
March 13th, 2006 at 9:41 am
How can i print 34 as 00034???
19. Ramkrishna Says:
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.
20. shaik rehaman Says:
March 23rd, 2006 at 5:58 am
great stuff to see about format funtion
21. Dave Markle Says:
March 23rd, 2006 at 12:15 pm
Steve –
THANK YOU so much for publishing this. >>Every
22. MikeG Says:
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 :)
23. Deepak Says:
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.
24. Matt Says:
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.
25. Oskar Austegard Says:
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%
26. Deli Shen Says:
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!
27. xill Says:
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
28. George Stylli Says:
April 24th, 2006 at 10:39 am
Thanks for this great piece of work!
Saved loads of time.
Cheers!
George
29. Dan Says:
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
30. Chemlock Says:
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
31. Ian Davis Says:
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!
32. Troubled Says:
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.
33. Ken Dourado Says:
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());
34. Steve Says:
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.
35. KierenH Says:
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.
36. Arsalkhan Says:
July 7th, 2006 at 2:51 pm
Great job dude keep it up ;)
37. wagn Says:
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
38. Elson Says:
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
39. Elson Says:
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
40. wagn Says:
July 18th, 2006 at 3:16 am
Thanks Elson it works
41. Paul Kahl Says:
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”?
42. mike Says:
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
43. Victor Says:
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
44. Jeannie Says:
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.
45. Tom Says:
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
46. gowrish.p Says:
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..
47. James Hancock Says:
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 :
48. Ericson Mar Says:
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
49. Mark Says:
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.
50. Riady Says:
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
‘ ‘ -> +
51. sougata Says:
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 ?
52. Al Says:
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.
53. jansi rajkumar Says:
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
54. freggel Says:
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
55. Denny Says:
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);
56. Bob Says:
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
57. Talha Says:
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.
58. Kimberly Says:
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
59. sunny Says:
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
60. Sandy Says:
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?
61. Sanjeewa. K. Says:
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?
62. Eugen M. Says:
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”
63. Alexis Junchaya Says:
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.
64. Gaurav Arya Says:
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….????
65. Rakesh Says:
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?
66. Dean Says:
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.
67. John S. Says:
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/
68. john whitt Says:
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.
69. eyal Says:
February 2nd, 2007 at 12:53 pm
How can I convert 1200 –> 1.2K?
1200000 –> 1.2M
70. khorner Says:
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)
71. khz Says:
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!
72. Chris Boley Says:
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, “#”)
73. Iftikar Says:
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
74. Serge Says:
February 16th, 2007 at 10:02 pm
> d Decimal (Whole number)
What is a “Decimal (Whole number)”? Sure sounds non-intuitive.
75. fooname Says:
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
76. Zytan Says:
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.
77. Cindy Says:
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?
78. Anonymous Says:
March 7th, 2007 at 6:20 am
So what do google ads G Strings for men have to do with your site Steve? :)
79. foolsday Says:
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!
80. lola Says:
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 ??
81. Robert Says:
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?
82. Robert Says:
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.
83. Jankrod Says:
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
84. James Says:
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,
85. Ryan Montgomery Says:
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.
86. Rob Volk Says:
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}
87. BeeKay Says:
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?
88. Stubby theCat Says:
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.
89. Manohar Says:
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)
90. Zytan Says:
May 6th, 2007 at 6:47 pm
{0:0,0} does not work for single digit numbers, it prefixes a 0.
91. Zytan Says:
May 7th, 2007 at 12:25 pm
Arne told me to use this: {0:#,0} instead, and it works!
92. Moose Says:
May 7th, 2007 at 12:27 pm
Great site, too bad Microsoft can not publish useful help. Thanks for the help.
93. Santosh Says:
May 23rd, 2007 at 4:58 am
How to format $32,000.00 as 32000 in C# ? can any one gimme an Idea ?
94. Shankar Says:
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
95. Ally Says:
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?
96. HM Says:
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.
97. rekhakrishnan Says:
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?
98. ajantha Says:
June 29th, 2007 at 2:33 am
how to convert exponents to number without exponent notation
99. Sohail Mahboob Says:
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
100. Dave Says:
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!
101. Umer Says:
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
102. Michael Hall Says:
July 26th, 2007 at 12:44 pm
You’ve been Kicked”.
103. Anastasiosyal Says:
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);
104. anurag Says:
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
105. az Says:
August 8th, 2007 at 11:30 pm
Sandeep Says:
March 13th, 2006 at 9:41 am
How can i print 34 as 00034???
106. Giannis Says:
August 13th, 2007 at 3:31 am
very helpful post surely worth to bookmark
107. Harry Says:
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?
108. Hiren Says:
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?
109. jessi Says:
August 18th, 2007 at 12:37 am
how many characters can be passed within a string?
110. jambunathan Says:
August 24th, 2007 at 11:33 pm
how to formating 8/25/2007,12:05:03PM into 25-Aug-2007.
111. wavounet Says:
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
112. Amit Choudhary Says:
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…
113. Virendra Says:
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.
114. Virendra Says:
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
115. Gill Bates Says:
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?
116. Bino Bose Says:
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
117. Doug Says:
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?
118. Omar Melendez Says:
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!
119. Ady Says:
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’);
120. don nielsen Says:
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
121. Michael Lang Says:
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}”);
122. Saurabh Says:
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#
123. hema Says:
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
124. enrique Says:
October 30th, 2007 at 1:22 pm
I would show -9.00 and +9.00 (sign included) with ToString() method… How?
125. Mike Says:
November 8th, 2007 at 3:43 am
Many thanks! Been looking for a summery like this for a while! Cheers! :)
126. Steve B. Says:
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???
127. Steve Trefethen Says:
November 15th, 2007 at 6:21 pm
Great post, I just found this. Thanks!
128. siva Says:
November 22nd, 2007 at 7:56 pm
How to format $32,000.00 as 32000 in C# ? can any one gimme an Idea ?
129. Shivraj Says:
November 24th, 2007 at 10:25 am
Thanks Steve u have solved my problem
130. cienio Says:
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 ???
131. Senthil Says:
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
132. SteveX Compiled » String Formatting in C# at DSharp Says:
December 17th, 2007 at 6:14 am
[...] SteveX Compiled » String Formatting in C# [...]
133. Publius Says:
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:#,#}”.
134. NXavier Says:
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.
135. NXavier Says:
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})”
:-)
136. Vijay Says:
January 14th, 2008 at 4:48 pm
Great post! Very comprehensive C# string formatting reference.
137. VBA parameterised string formatting « Latest Misunderstandings Says:
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. [...]
138. IT help south of france Says:
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.
139. removals to france Says:
January 25th, 2008 at 7:21 am
im sure you should do Convert.ToDecimal(var)) before you use the format method
140. MattS Says:
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.
141. Kaushal Says:
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
142. Jamelle Says:
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!!!!!!
143. Ben Joyce Says:
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
144. Formatando String - Eduardo Spaki Says:
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, [...]
145. crocodilu Says:
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 ?
146. Jolly Says:
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.
147. Tao Designs Weblog » string formatting in c# Says:
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 [...]
148. Ellis Web » Items of Interest: 2006.07.19 Says:
August 14th, 2008 at 9:27 am
[...] String Formatting in C# - Nice guide by Steve Tibbett (via the Daily Grind) [...]
149. Some String Formatting Examples with C# at { null != Steve } Says:
August 20th, 2008 at 8:32 am
[...] http://blog.stevex.net/index.php/string-formatting-in-csharp/ [...]
150. moondaddy Says:
August 23rd, 2008 at 11:03 am
Pad numbers with zero:
int num = 2;
string str = num.ToString(”00″);
Console.WriteLine(str);
// returns “02″
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″.
150 Responses to “String Formatting in C#”
1. stevex » Blog Archive » Different Theme Says:
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. [...]
2. pwalls Says:
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.
3. Tim Lewis Says:
November 23rd, 2005 at 10:51 am
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:
November 25th, 2005 at 2:17 pm
I want format String
string.format(”00-0000″),myhouse);
my-house?
5. murugan.g Says:
December 8th, 2005 at 9:30 am
Hi Steve,
Thanks for this wonderful article.
How can i format date like this “December 08th, 2005″.
6. Jorge de Cardenas Says:
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
7. Jeremy Says:
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.
8. stevex Says:
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.
9. Krise Says:
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
10. Broads Says:
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
11. Philippe Quesnel Says:
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
12. Philippe Quesnel Says:
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
13. tom callaghan Says:
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
14. ddegenaro Says:
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!
15. Michael Says:
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
16. Gunnar Olerud Says:
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
17. Bob Bedell Says:
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
18. Sandeep Says:
March 13th, 2006 at 9:41 am
How can i print 34 as 00034???
19. Ramkrishna Says:
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.
20. shaik rehaman Says:
March 23rd, 2006 at 5:58 am
great stuff to see about format funtion
21. Dave Markle Says:
March 23rd, 2006 at 12:15 pm
Steve –
THANK YOU so much for publishing this. >>Every
22. MikeG Says:
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 :)
23. Deepak Says:
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.
24. Matt Says:
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.
25. Oskar Austegard Says:
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%
26. Deli Shen Says:
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!
27. xill Says:
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
28. George Stylli Says:
April 24th, 2006 at 10:39 am
Thanks for this great piece of work!
Saved loads of time.
Cheers!
George
29. Dan Says:
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
30. Chemlock Says:
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
31. Ian Davis Says:
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!
32. Troubled Says:
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.
33. Ken Dourado Says:
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());
34. Steve Says:
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.
35. KierenH Says:
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.
36. Arsalkhan Says:
July 7th, 2006 at 2:51 pm
Great job dude keep it up ;)
37. wagn Says:
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
38. Elson Says:
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
39. Elson Says:
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
40. wagn Says:
July 18th, 2006 at 3:16 am
Thanks Elson it works
41. Paul Kahl Says:
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”?
42. mike Says:
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
43. Victor Says:
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
44. Jeannie Says:
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.
45. Tom Says:
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
46. gowrish.p Says:
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..
47. James Hancock Says:
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 :
48. Ericson Mar Says:
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
49. Mark Says:
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.
50. Riady Says:
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
‘ ‘ -> +
51. sougata Says:
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 ?
52. Al Says:
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.
53. jansi rajkumar Says:
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
54. freggel Says:
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
55. Denny Says:
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);
56. Bob Says:
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
57. Talha Says:
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.
58. Kimberly Says:
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
59. sunny Says:
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
60. Sandy Says:
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?
61. Sanjeewa. K. Says:
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?
62. Eugen M. Says:
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”
63. Alexis Junchaya Says:
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.
64. Gaurav Arya Says:
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….????
65. Rakesh Says:
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?
66. Dean Says:
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.
67. John S. Says:
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/
68. john whitt Says:
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.
69. eyal Says:
February 2nd, 2007 at 12:53 pm
How can I convert 1200 –> 1.2K?
1200000 –> 1.2M
70. khorner Says:
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)
71. khz Says:
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!
72. Chris Boley Says:
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, “#”)
73. Iftikar Says:
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
74. Serge Says:
February 16th, 2007 at 10:02 pm
> d Decimal (Whole number)
What is a “Decimal (Whole number)”? Sure sounds non-intuitive.
75. fooname Says:
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
76. Zytan Says:
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.
77. Cindy Says:
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?
78. Anonymous Says:
March 7th, 2007 at 6:20 am
So what do google ads G Strings for men have to do with your site Steve? :)
79. foolsday Says:
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!
80. lola Says:
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 ??
81. Robert Says:
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?
82. Robert Says:
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.
83. Jankrod Says:
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
84. James Says:
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,
85. Ryan Montgomery Says:
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.
86. Rob Volk Says:
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}
87. BeeKay Says:
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?
88. Stubby theCat Says:
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.
89. Manohar Says:
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)
90. Zytan Says:
May 6th, 2007 at 6:47 pm
{0:0,0} does not work for single digit numbers, it prefixes a 0.
91. Zytan Says:
May 7th, 2007 at 12:25 pm
Arne told me to use this: {0:#,0} instead, and it works!
92. Moose Says:
May 7th, 2007 at 12:27 pm
Great site, too bad Microsoft can not publish useful help. Thanks for the help.
93. Santosh Says:
May 23rd, 2007 at 4:58 am
How to format $32,000.00 as 32000 in C# ? can any one gimme an Idea ?
94. Shankar Says:
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
95. Ally Says:
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?
96. HM Says:
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.
97. rekhakrishnan Says:
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?
98. ajantha Says:
June 29th, 2007 at 2:33 am
how to convert exponents to number without exponent notation
99. Sohail Mahboob Says:
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
100. Dave Says:
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!
101. Umer Says:
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
102. Michael Hall Says:
July 26th, 2007 at 12:44 pm
You’ve been Kicked”.
103. Anastasiosyal Says:
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);
104. anurag Says:
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
105. az Says:
August 8th, 2007 at 11:30 pm
Sandeep Says:
March 13th, 2006 at 9:41 am
How can i print 34 as 00034???
106. Giannis Says:
August 13th, 2007 at 3:31 am
very helpful post surely worth to bookmark
107. Harry Says:
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?
108. Hiren Says:
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?
109. jessi Says:
August 18th, 2007 at 12:37 am
how many characters can be passed within a string?
110. jambunathan Says:
August 24th, 2007 at 11:33 pm
how to formating 8/25/2007,12:05:03PM into 25-Aug-2007.
111. wavounet Says:
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
112. Amit Choudhary Says:
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…
113. Virendra Says:
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.
114. Virendra Says:
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
115. Gill Bates Says:
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?
116. Bino Bose Says:
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
117. Doug Says:
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?
118. Omar Melendez Says:
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!
119. Ady Says:
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’);
120. don nielsen Says:
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
121. Michael Lang Says:
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}”);
122. Saurabh Says:
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#
123. hema Says:
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
124. enrique Says:
October 30th, 2007 at 1:22 pm
I would show -9.00 and +9.00 (sign included) with ToString() method… How?
125. Mike Says:
November 8th, 2007 at 3:43 am
Many thanks! Been looking for a summery like this for a while! Cheers! :)
126. Steve B. Says:
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???
127. Steve Trefethen Says:
November 15th, 2007 at 6:21 pm
Great post, I just found this. Thanks!
128. siva Says:
November 22nd, 2007 at 7:56 pm
How to format $32,000.00 as 32000 in C# ? can any one gimme an Idea ?
129. Shivraj Says:
November 24th, 2007 at 10:25 am
Thanks Steve u have solved my problem
130. cienio Says:
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 ???
131. Senthil Says:
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
132. SteveX Compiled » String Formatting in C# at DSharp Says:
December 17th, 2007 at 6:14 am
[...] SteveX Compiled » String Formatting in C# [...]
133. Publius Says:
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:#,#}”.
134. NXavier Says:
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.
135. NXavier Says:
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})”
:-)
136. Vijay Says:
January 14th, 2008 at 4:48 pm
Great post! Very comprehensive C# string formatting reference.
137. VBA parameterised string formatting « Latest Misunderstandings Says:
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. [...]
138. IT help south of france Says:
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.
139. removals to france Says:
January 25th, 2008 at 7:21 am
im sure you should do Convert.ToDecimal(var)) before you use the format method
140. MattS Says:
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.
141. Kaushal Says:
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
142. Jamelle Says:
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!!!!!!
143. Ben Joyce Says:
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
144. Formatando String - Eduardo Spaki Says:
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, [...]
145. crocodilu Says:
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 ?
146. Jolly Says:
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.
147. Tao Designs Weblog » string formatting in c# Says:
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 [...]
148. Ellis Web » Items of Interest: 2006.07.19 Says:
August 14th, 2008 at 9:27 am
[...] String Formatting in C# - Nice guide by Steve Tibbett (via the Daily Grind) [...]
149. Some String Formatting Examples with C# at { null != Steve } Says:
August 20th, 2008 at 8:32 am
[...] http://blog.stevex.net/index.php/string-formatting-in-csharp/ [...]
150. moondaddy Says:
August 23rd, 2008 at 11:03 am
Pad numbers with zero:
int num = 2;
string str = num.ToString(”00″);
Console.WriteLine(str);
// returns “02″
> 我来回应
热门话题 · · · · · · ( 去话题广场 )
- 独居中年女性最难面对的困境1.0万+篇内容 · 8.0万次浏览
- 让人生变开阔的方法1.0万+篇内容 · 870.2万次浏览
- 我的生命和夏天是同一种质地21篇内容 · 1.4万次浏览
- 中年人感悟特别多2432篇内容 · 1263.8万次浏览
- 梗图续命,笑到通气57篇内容 · 178.9万次浏览
- 谈过很多次恋爱后才明白的道理276篇内容 · 243.4万次浏览
- 你见过最离谱的AI幻觉170篇内容 · 3.6万次浏览
- 身为女性你有哪些想要逃离的瞬间99篇内容 · 51.7万次浏览