Saturday, December 13, 2008 12:48 AM
If I could get a dollar for every missing .NET function, I'll be a millionaire by now but again, they can only write so much. With my current project, I needed a way to display numbers that are really large such as hundreds of thousands and millions. Its a whole lot cleaner when your interface displays 104.6K than 104,600 or 1.5M instead of 1,500,000 or better yet some obscure number such as 1,345,2356,344 - its just hard to read and messes with you tabular display.
Anyway, here is quick run down on how you can format your numbers nicely, feel free to let me know if there is a better or faster way, since I got this from Google and common sense.
1: public static string FormatToFriendlyNumber(decimal numToFormat)
2: {
3: string[] symbol = { string.Empty, "k", "M", "G", "T", "P" };
4:
5: int symIndex = (Convert.ToString(numToFormat).Length - 1) / 3;
6: double prefix = Math.Pow(1000, (double)symIndex);
7: double fNum = ((double)numToFormat / prefix);
8:
9: return string.Concat(fNum.ToString("#.##"), symbol[symIndex]);
10: }