Aligning numbers on their decimal point
In order to align numbers on their decimal point with
String.Format
, something like
{p,w:Fa}
can be chosen:
-
p
indicates which value is formatted
-
w
specifies the total width, including decimal point and optional sign
-
F
is the literal letter F
that specifies that the numbers are to be aligned on their decimal point.
-
a
is the number of digits afther the decimal point.
In the following example, the format specification is {1,8:F3}
.
using System;
class Prg {
public static void Main() {
var nums = new object[] { 42, 12.34567, null, 7.1F, 9876.54321, -333.3333333, 17.17M };
foreach (var num in nums) {
Console.WriteLine(String.Format(
" {0,-20}: {1,8:F3}",
num == null ? "null" : num.GetType().FullName,
num
));
}
}
}
//
// System.Int32 : 42.000
// System.Double : 12.346
// null :
// System.Single : 7.100
// System.Double : 9876.543
// System.Double : -333.333
// System.Decimal : 17.170