Mega Code Archive

 
Categories / C# Book / 02 Essential Types
 

0288 Custom format and a format provider

format and format provider are linked by IFormattable interface. All numeric types and DateTime DateTimeOffset implement this interface: public interface IFormattable { string ToString (string format, IFormatProvider formatProvider); } The first argument is the format string. The second is the format provider. The format string provides instructions. The format provider does the format based on the instructions. using System; using System.Text; using System.Globalization; class Sample { public static void Main() { NumberFormatInfo f = new NumberFormatInfo(); f.CurrencySymbol = "$$"; Console.WriteLine(3.ToString("C", f)); // $$ 3.00 } } The output: $$3.00 "C" is a format string NumberFormatInfo object is a format provider. If you specify a null format string or provider, a default is applied The default format provider is CultureInfo.CurrentCulture. using System; using System.Text; using System.Globalization; class Sample { public static void Main() { Console.WriteLine(10.3.ToString("C", null)); } } The output: $10.30 Most types overload ToString such that you can omit the null provider using System; using System.Text; using System.Globalization; class Sample { public static void Main() { Console.WriteLine(10.3.ToString("C")); Console.WriteLine(10.3.ToString("F4")); } } The output: $10.30 10.3000 The .NET Framework defines three format providers: NumberFormatInfo DateTimeFormatInfo CultureInfo CultureInfo is a proxy for the other two format providers. It returns a NumberFormatInfo or DateTimeFormatInfo object applicable to the culture's regional settings. using System; using System.Text; using System.Globalization; class Sample { public static void Main() { CultureInfo uk = CultureInfo.GetCultureInfo("en-GB"); Console.WriteLine(3.ToString("C", uk)); } }