Format a String as Currency in C#

When building a string for output to a web page, it’s useful to format any currency value in a human-friendly money format. This is extremely easy in C#.

The system format string works like this: {0:C}

For example, the following code example:

decimal moneyvalue = 1921.39m;
string html = String.Format("Order Total: {0:C}", moneyvalue);
Console.WriteLine(html);

Outputs the following:

Order Total: $1,921.39

It’s worth noting that you must pass in a numeric value to the String.Format statement. If you pass in a string value, it won’t format correctly. If your currency value is in a string, you need to convert it into a double first.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

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: