09 June, 2009

Custom Thousand Separator In C#

I guess the NFA requires us to use a space (" ") instead of a comma (",") as our thousands separator. I dunno why the have to regulate something like that, but I had to figure out an elegant way to format our numbers the way the powers that be require them to be formatted.

After struggling with different inelegant solutions for a little while, I finally realized that different countries use different symbols as thousands separators; I knew then that my problem was really a localization problem. A quick search in MSDN lead me to the NumberFormatInfo class, which "defines how numeric values are formatted and displayed, depending on the culture" (MSDN).

The NumberFormatInfo class, has a NumberGroupSeparator property that defines what character to use to separate thousands.

So, here's how I ended up solving my problem:

public void FormatDouble(double doubleToFormat)
NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
nfi.NumberGroupSeparator = " ";
Write(doubleToFormat.ToString("n", nfi);

Neat, huh?


Mike Munoz - CCIE 9751 said...

How do you input code into the blog with the line numbers?


Esteban Araya said...


I use SyntaxHighlighter; you can find it at http://code.google.com/p/syntaxhighlighter/

There's also plenty of other good "code prettyfiers" available.

Post a Comment