Jun 24, 2012

(C#) String formatting with custom IFormatProvider

2 comments
Following example shows how to write a custom IFormatProvider which you can use in method String.Format(I­FormatProvider, …).

This formatter formats doubles to 3 decimal places with a dot(.) separator.
Code:
public class DoubleFormatter : IFormatProvider, ICustomFormatter
{
  // always use dot separator for doubles
  private CultureInfo enUsCulture = CultureInfo.GetCultureInfo("en-US");

  public string Format(string format, object arg, IFormatProvider formatProvider)
  {
    // format doubles to 3 decimal places
    return string.Format(enUsCulture, "{0:0.000}", arg);
  }

  public object GetFormat(Type formatType)
  {
    return (formatType == typeof(ICustomFormatter)) ? this : null;
  }
}

Now we have custom formatter and let's see how to use this,

double width = 10.34556;
double height = 11.23476;
Console.WriteLine(
  string.Format(new DoubleFormatter(), "Width={0}\n Height={1}", width, height));

Output:

Width=10.346
Height=11.235


So now we have a reusable format for doubles(3 decimal places with dot separator). That is nice, but this formatter is very simple – it formats everything (eg. DateTime) as "0:000".

The complete source code looks like as shown below,

public class DoubleFormatter : IFormatProvider, ICustomFormatter
{
  // always use dot separator for doubles
  private CultureInfo enUsCulture = CultureInfo.GetCultureInfo("en-US");

  public string Format(string format, object arg, IFormatProvider formatProvider)
  {
    if (arg is double)
    {
      if (string.IsNullOrEmpty(format))
      {
        // by default, format doubles to 3 decimal places
        return string.Format(enUsCulture, "{0:0.000}", arg);
      }
      else
      {
        // if user supplied own format use it
        return ((double)arg).ToString(format, enUsCulture);
      }
    }
    // format everything else normally
    if (arg is IFormattable)
      return ((IFormattable)arg).ToString(format, formatProvider);
    else
      return arg.ToString();
  }

  public object GetFormat(Type formatType)
  {
    return (formatType == typeof(ICustomFormatter)) ? this : null;
  }
}


If you feel this is helpful or you like it, Please share this using share buttons available on page.

2 comments :

  1. I am very thankful to the author to write this fruitful information.It is worth sharing for other users.Thanks once again
    access Mp3lemon in UK

    ReplyDelete