
There are tons of options for custom formatting a number, but not enough :)
Let's take a series of double/decimal numbers:
1: double[] doubles = {
2: -1234.56789, 3: 1234.56789, 4: 1234.5678, 5: 1234.56, 6: 1234.5, 7: 1234.56789, 8: 123.56789, 9: 12.56789, 10: 1.56789, 11: .56789, 12: -.56789, 13: };One classic way to format those numbers is the following:
1: string fmt = "####0.0000";
2: foreach(var d in doubles)
3: Console.WriteLine(d.ToString(fmt));That unfortunately give this result:
1: -1234,5679 2: 1234,5679 3: 1234,5678 4: 1234,5600 5: 1234,5000 6: 1234,5679 7: 123,5679 8: 12,5679 9: 1,5679 10: 0,5679 11: -0,5679Since I needed to align the numbers in a diagnostic trace to the decimal separator, I wrote a little extension method that does the trick:
1: public static class FormatHelper
2: {3: public static string ToStringAligned(this double d, string Format)
4: {5: string t = d.ToString(Format);
6: if(Format.Length - t.Length < 0)
7: return t;
8: return string.Format("{0}{1}", new string(' ', Format.Length - t.Length), t);
9: } 10: 11: public static string ToStringAligned2(this double d, string Format)
12: {13: return string.Format("{0," + Format.Length + ":" + Format + "}", d);
14: } 15: }Those two methods are equivalent. The second is shorter and probably the better. Since the syntax "{0,10:####0.0000}" still need to be parsed, maybe the second is not the faster. Should give a try under a stopwatch to have the answer. Furthermore with the first one I can choose the padding character. For example in a Html output the padding would be " ".
The modified code to use this extension is as much as simple:
1: foreach(var d in doubles)
2: Console.WriteLine(d.ToStringAligned(fmt));And finally this is was I wanted to obtain:
1: -1234,5679 2: 1234,5679 3: 1234,5678 4: 1234,5600 5: 1234,5000 6: 1234,5679 7: 123,5679 8: 12,5679 9: 1,5679 10: 0,5679 11: -0,5679Yes, no revolutions, nothing magic, but it just works.
Copyright (c) Raffaele Rialdi 2009, Senior Software Developer, Consultant, p.iva IT01741850992, hosted by Vevy Europe Advanced Technologies Division. Site created by Raffaele Rialdi, 2009 - 2011