.NET (C#) – format decimal as price – with no culture specific information and two decimal points
07/08/2011 Leave a Comment
This is one of those where there’s so many ways of doing something simple – you end up going “will someone please just tell me how the…” etc etc :0)
The below is a simple basic way, which ignores all culture specific information (you add the currency symbol yourself), and gives you two decimal points.
decimal decimalValue = 12.99M;
string test = String.Format("Item costs £{0:N} only", decimalValue);
//"Item costs £12.99 only"
//This will also round correctly - e.g. 12.995 to "13.00", and 12.994 to "12.99".
And if you need to inject the currency symbol based on some logic:
string currencySymbol = "£";
string test = String.Format("Item costs {0}{1:N} only", currencySymbol, decimalValue);
//"Item costs £12.99 only"
And then of course finally we stick this into an extension method:
public static class ExtDecimal
{
public static string ToMoney(this Decimal d, string currencySymbol)
{
return String.Format("{0}{1:N}", currencySymbol, d);
}
}
...
string test = decimalValue.ToMoney("£");
//"£12.99" - and above example:
test = String.Format("Item costs {0} only", decimalValue.ToMoney("£"));
//"Item costs £12.99 only"