Monday, 3 March 2008

using .Net ToString() to format currency values

A nice little bit of code to help display decimal values as currency and using the ever so helpful ToString() method. All you do is add in some format info as show below to tell it to format the string as a currency.

decimal myMoney = 142.00;
string formattedString = myMoney.ToString("c0");

It will use the CurrentInfo property of System.Globalization.NumberFormatInfo the localization information to work out what currency to use. So for me the formatted string would be £142. The zero in the format string sets the number of decimal places to use.

To convert this value back to a decimal you can use this code below.

decimal myMoney = Decimal.Parse(formattedString , NumberStyles.Currency);

Just to be safe wrap this in a try catch block to catch System.FormatException errors which means that someone entered a value using the wrong currency type. SO if the CurrentInfo says the local currency should be US dollars $142 and someone uses pounds £142 instead it will complain.

Right cool, think that's just about that.


No comments: