.NET Zone is brought to you in partnership with:

I am Microsoft C# MVP July - 2012 My name is Pranay Rana. Currently, I'm working as senior software engineer in a mid-sized company (Ahmedabad). I have 5 years of the experience in web development with Asp.Net, C# and MS SQL server. For me, the definition of programming is: something that you do once and that gets used by multiple users for many years Pranay is a DZone MVB and is not an employee of DZone and has posted 34 posts at DZone. You can read more from them at their website. View Full User Profile

Display and Format Negative Currency Values in C#

  • submit to reddit

This small tip about how to show the negative currency value in your application. For Example if you have currency value like -1234 and you want to display it like -$1,234 according to you culture.

In C# to one of the way to format currency value easily is use ToString("c") with value will do work for you. For example check below code

//format -1234 as currency..

This will display value in output like this ($1,234.00). But the actual problem with the formatting is its not displaying - sign with currency value.
So to come out of this You need to create a custom NumberFormatInfo from your current locale. Then you can specify it's CurrencyNegativePattern, for example:

CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
CultureInfo newCulture = new CultureInfo(currentCulture.Name);
newCulture.NumberFormat.CurrencyNegativePattern = 1;
Thread.CurrentThread.CurrentCulture = newCulture;

Now output of the above code is -$1,234.00. That's what actually needed display negative sign for negative currency value.
So in above code actual trick done by NumberFormatInfo.CurrencyNegativePattern Property, which is set to 1 which associated with pattern -$n. There number of different pattern supported which you can check on MSDN and assign value to property according to your need. This will not affect positive value of currency i.e. if you pas 1234 as value its dispaly as $1,234 only. And for this this example my current culture is "en-US" .

I Hope you all like this simple and easy example of formatting negative currency. you can explore more on MSDN on reference provided at end of post.
NumberFormatInfo Classhttp://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx
NumberFormatInfo.CurrencyNegativePattern Property - http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencynegativepattern.aspx

Published at DZone with permission of Pranay Rana, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)