I'm looking for a consistent way to structure my use of formatting strings throughout a large web application, and I'm looking for recommendations or best practices on which way to go.
Up until now I've had a static class that does some common formatting e.g.
Formatting.FormatCurrency
Formatting.FormatBookingReference
I'm not convinced that this is the way to go though, I'd prefer to use the standard way of formatting strings within .NET directly and use:
amount.ToString("c")
reference.ToString("000000")
Id use IFormattable and ICustomFormatter for some of our more complicated data structures, but I'm struggling what to do about the more simple existing objects that we need to format (in this case Int32 but also DateTime).
Do I simply define constants for "c" and "000000" and use them consistently around the whole web app or is there a more standard way to do it?
One option is to use a helper class with extension methods like
public static class MyWebAppExtensions
{
public static string FormatCurrency(this decimal d)
{
return d.ToString("c");
}
}
Then anywhere you have a decimal value you do
Decimal d = 100.25;
string s = d.FormatCurrency();
I agree with GeekyMonkey's suggestion, with one alteration:
Formatting is an implementation detail. I would suggest ToCurrencyString
to keep with the To* convention and its intent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With