Sonntag, 28. August 2016

String to Double value conversion

In different cultures differs the decimal delimiter. Therfore you could profit by such an extension method like this one. So it doesn't matter if you are using a english or german client, when converting for instance "4711.10" or "4711,10" to a double value.

        //english/Invariant system . = decimal delimiter
        //DE, NL system            , = decimal delimiter
        public static double ToDoubleEx<T>(this T obj)
        {
            if (obj == null) return 0;
            double result = 0;
            string v = Convert.ToString(obj);
            if (v != null && v.Length > 0)
            {
                var point = v.IndexOf('.');
                var komma = v.IndexOf(',');
                if (point != -1 && komma != -1)
                {
                    if (komma > point)
                        v = v.Replace(".", "");
                    else
                        v = v.Replace(",", "");
                }
                v = v.Replace(",", ".");
                result = Double.Parse(v, System.Globalization.CultureInfo.InvariantCulture); //Invariant behavior like english default behavior
            }
            return result;
        }

Benefit from the best Windows Desktop app in the world and use Strokey.Net!