Demo entry 4788108

sas

   

Submitted by anonymous on May 17, 2016 at 21:11
Language: C#. Code size: 940 Bytes.

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;
  }
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).