Search notes:

.NET: String.Format

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:
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
Github repository .NET-API, path: /System/String/Format/align-decimal-point.cs

See also

The PowerShell operator -f uses String.Format under the hood.

Index