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  

About the Author

Adnan Zameer, Lead Developer at Optimizley UK, is a certified Microsoft professional, specializing in web app architecture. His expertise includes Optimizley CMS and Azure, showcasing proficiency in crafting robust and efficient solutions.

0 comments :

Post a Comment