Monday, 8 September 2014

Function to Convert Decimal to string Culture monetry value and Revert it back to Decimal

You can use the following functions to convert a Decimal Monetary value according to specified culture.And Revert it back to decimal.

//Function to convert Decimal Monetary value to Culture format i.e Swedish Kronor in example 
public static string formatMoney(Decimal d)
{
   return String.Format(System.Globalization.CultureInfo.CreateSpecificCulture("sv-SE"), "{0:C}", d);
}

//Function to convert  Culture format Monetary value i.e Swedish Kronor to Decimal Monetary value 
public static Decimal parseMoney(string money)
{
     return Decimal.Parse(
                        money,
                        System.Globalization.NumberStyles.Currency,
                        System.Globalization.CultureInfo.CreateSpecificCulture("sv-SE")
                        );
}

This will throw an exception if money is not correctly formatted for the culture specified.  Use TryParse if you do not want to throw an exception

/Adnan




Note: This post is from my old blog posted on  May 2011, that unfortunately no longer exist  

0 comments :

Post a comment