.NET (C#) – format decimal as price – with no culture specific information and two decimal points

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"
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: