Monday, January 29, 2007

formatting 0, 1 as yes, no or whatever

This is something we all have done at some point, convert a 0,1 value into yes, no, on, off, etc string

turns out there is a function in the BCL that can do this, string.Format will do the job

Console.WriteLine(string.Format("{0:yes;;no}", 0)); //will output "no"
Console.WriteLine(string.Format("{0:yes;;no}", 1)); //will ouput "yes"


and just for the heck of it
Console.WriteLine(string.Format("{0:yes;;no}", -1)); //will output "-yes"

...one of those little thingies

3 comments:

Anonymous said...

Great! This is very convenient. Also for databinding within ASP.NET.

BlackTigerX said...

there you go, that's an interesting use of this thingie

James Curran said...

Of course, what you are actually doing is specifying format strings. {0:yes;;no} translates to
{position:positive format;negative format; zero format}. A more convention use would be:
{0:###.##;(###.##);-zero-}