Wednesday, 15 September 2010

.NET String Formatting Cheat Sheet

This morning I saw this tweet from @jhollingworth:image

which linked to this excellent guide to .NET string formats by Steve Tibbett

Sometimes, something is just so incredibly useful that even bookmarking it isn’t convenient enough – so I’ve hacked Steve’s guide and examples into a one-page A4 cheat sheet and stuck it on the wall next to my desk.

image It’s up on my site as a PDF or as a Word document – download it, print it out, stick it on the wall, and you’ll never find yourself Googling {0:n} vs {0:c} again.

All credit to Steve Tibbett for this – all I did was make it fit on one printed page. Happy formatting.

3 comments:

Anonymous said...

Thanks, That is super useful. You should add it to the community content on MSDN. http://msdn.microsoft.com/en-us/library/system.string.format(v=VS.90).aspx

Luc C. said...

Very nice list indeed! What I missed though was the effect 'precision' specifications have on the output and I had to look at the MSDN docs to discover that 'd' and 'D' seem to be the same.

In particular I missed the zero-padding implied by 'D': String.Format("{0:D5}",42) which gives "00042" (the same as the "{0:00000}" example, but a bit shorter).

Anonymous said...

Great cheat sheet!

I noticed that the first sample actually is incorrect. A negative number adds padding to the right and a positive adds padding to the left. This is mixed in the sample provided. Besides, the index needs to be 0, not 1.

It would be great if you updated the PDF version.