Thursday, February 21, 2008

Convert percent string to double

In .NET, it's easy to convert a number to a percentage:


double value = .45;
string formatted = value.ToString("p", CultureInfo.CurrentUICulture);



No big deal. Comes out as "45.00 %" for many cultures. It's similar for the others, which things like 4"5,00 % ". Always multiplies the number by 100. Easy.

But converting it back to a double isn't so easy. double.Parse and TryParse don't work with percentages. After looking on the web for a while, I didn't find a good solution. I needed it to work for all cultures and be pretty forgiving in the input it allowed. So here's my solution:


        static double ConvertPercentageToDouble(string formattedNumber)

        {

            return ConvertPercentageToDouble(formattedNumber,CultureInfo.CurrentCulture);

        }

 

        static double ConvertPercentageToDouble(string formattedNumber, System.Globalization.CultureInfo cultureInfo)

        {

            if (string.IsNullOrEmpty(formattedNumber))

                throw new ArgumentNullException("formattedNumber");

 

            formattedNumber = formattedNumber.Replace(cultureInfo.NumberFormat.PercentSymbol, string.Empty);

 

            double value = double.Parse(formattedNumber, NumberStyles.Any, cultureInfo);

            if (value != 0)

                value /= 100.0;

 

            return value;

        }

Looking good, no?

1 comment:

Unknown said...

This works great, except Replace() will throw an exception if there's no percent symbol in the text.