Custom formatter : It helps in specifying formatter for our application.
It is very handy when we want common format across our application.i.e. datetime,decimal formatting.
Custom Formatter
How to provide custom format to out datetime,decimal values across out application.>
Solution
Typically we use toString(< format >) or string.format(< format > ) to provide custom formatting to our application but to make it identcal formatting(Could be configurable) across our application is difficult.
Following snippet shows how we can create framework that makes sure that formatting should be configurable and identical across.
public class ApplicationFormatter
{
public static string GetFormattedString(object obj)
{
string formattedString = string.Empty;
if (obj is double)
{
formattedString = string.Format(new DecimalFormatter(), "{0}", (double)obj);
}
else if (obj is DateTime)
{
formattedString = string.Format(new DateFormatter(), "{0}", (DateTime)obj);
}
return (formattedString);
}
}
public class DecimalFormatter : IFormatProvider, ICustomFormatter
{
private CultureInfo threadCulture = Thread.CurrentThread.CurrentCulture;
//If you want to use some other culture.
//private CultureInfo threadCulture = CultureInfo.GetCultureInfo("en-US");
public string Format(string format, object arg, IFormatProvider formatProvider)
{
// format doubles up to 2 decimal places
//{0:0.00} can be configured. It will help to change
// decimal formatting all across application.
string formatter = ConfigurationManager.AppSettings["DecimalFormat"].ToString();
return string.Format(threadCulture,formatter, arg);
}
public object GetFormat(Type formatType)
{
return (formatType == typeof(ICustomFormatter)) ? this : null;
}
}
public class DateFormatter : IFormatProvider, ICustomFormatter
{
private CultureInfo threadCulture = Thread.CurrentThread.CurrentCulture;
//If you want to use some other culture.
//private CultureInfo threadCulture = CultureInfo.GetCultureInfo("en-US");
public string Format(string format, object arg, IFormatProvider formatProvider)
{
// format datetime to given format.
//{0:0.00} can be configured. It will help to change
// decimal formatting all across application.
string formatter = ConfigurationManager.AppSettings["DateFormat"].ToString();
return string.Format(threadCulture, formatter, arg);
}
public object GetFormat(Type formatType)
{
return (formatType == typeof(ICustomFormatter)) ? this : null;
}
}
protected void Page_Load(object sender, EventArgs e)
{
double d = 4.123456;
DateTime dateT = DateTime.Now;
string format1 = ApplicationFormatter.GetFormattedString(d);
string format2 = ApplicationFormatter.GetFormattedString(dateT);
}
Web.Config
< appSettings >
< add key="DateFormat" value="{0:MM/dd/yyyy}"/ >
< add key="DecimalFormat" value="{0:0.00}"/ >
< /appSettings >
