CSharp - Format Format Providers

Introduction

IFormattable interface handles the custom format.

public interface IFormattable{
   string ToString (string format, IFormatProvider formatProvider);
}

The first argument is the format string and the second is the format provider.

The format string provides instructions and the format provider determines how the instructions are implemented.

For example:

Demo

using System;
using System.Globalization;

class MainClass//from   w w w .ja va  2  s.  co  m
{
    public static void Main(string[] args)
    {
        NumberFormatInfo f = new NumberFormatInfo();
        f.CurrencySymbol = "$$";
        Console.WriteLine(3.ToString("C", f));
    }
}

Result

"C" is a format string that indicates currency, and the NumberFormatInfoobject is a format provider that determines how currency-and other numeric representations-are rendered.

If you specify a null format string or provider, a default is applied.

The default format provider is CultureInfo.CurrentCulture, which uses the computer's runtime control panel settings.

For example

Console.WriteLine (10.3.ToString ("C", null));  // $10.30

Most types overload ToString such that you can omit a null provider:

Console.WriteLine (10.3.ToString ("C"));     // $10.30
Console.WriteLine (10.3.ToString ("F4"));    // 10.3000 (Fix to 4 D.P.)

C# defines three format providers which all implement IFormatProvider:

  • NumberFormatInfo
  • DateTimeFormatInfo
  • CultureInfo

Demo

using System;
class MainClass//  w w w.j av a  2s.co  m
{
   public static void Main(string[] args)
   {
        Console.WriteLine (10.3.ToString ("C", null));  // $10.30
        Console.WriteLine (10.3.ToString ("C"));     // $10.30
        Console.WriteLine (10.3.ToString ("F4"));    // 10.3000 (Fix to 4 D.P.)
   }
}

Result