Monday, May 16, 2011

Aligning Numbers on the Decimal Separator [Ron Petrusha]

The composite formatting feature in the .NET Framework makes it easy to left-align or right-align a value in a fixed-width field. If the alignment component of a format item in a composite format string is negative, its corresponding argument is left-aligned. If the alignment component is positive, its corresponding argument is right-aligned. For instance, the following example assigns random numbers to an eleven-element array and displays their values. In the output, the array index is left-aligned in a five-character field, and the array value is right-aligned in a twelve-character field.

[Visual Basic]
Dim rnd As New Random()
Dim values(10) As Double
Console.WriteLine("{0,-5}{1,12}", "Index", "Value")
For ctr As Integer = values.GetLowerBound(0) To values.GetUpperBound(0)
    values(ctr) = rnd.NextDouble()
    Console.WriteLine(" {0,-5} {1,12:F6}", ctr, values(ctr))
Next

[C#]
Random rnd = new Random();
double[] values = new double[11];
Console.WriteLine("{0,-5}{1,12}", "Index", "Value");
for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
{
   values[ctr] = rnd.NextDouble();
   Console.WriteLine(" {0,-5} {1,12:F6}", ctr, values[ctr]);
}

The example produces output similar to the following:

Index      Value
 0         0.682236
 1         0.827866
 2         0.927542
 3         0.670535
 4         0.023612
 5         0.353050
 6         0.685052

Read more: BCL Team Blog