How to convert a dual culture using TypeConverter?

I have a problem with the class TypeConverter. It works great with values CultureInvariant, but cannot transform certain cultures, such as the English thousands separators. Below is a small test program in which I cannot work.

Here's the problem :) - ConvertFromStringthrows an exception with the following message: "2999.95 is not a valid value for Double." and with an internal exception. The input string is not in the correct format.

using System;
using System.Globalization;
using System.ComponentModel;

class Program
{
    static void Main()
    {
        try
        {
            var culture = new CultureInfo("en");
            var typeConverter = TypeDescriptor.GetConverter(typeof(double));
            double value = (double)typeConverter.ConvertFromString(
                null, 
                culture, 
                "2,999.95");

            Console.WriteLine("Value: " + value);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }
}

Edit: Link to Connect Error Report

+3
source share
1 answer

DoubleConverter, TypeDescriptor.GetConverter(typeof(double)), Double.Parse :

Double.Parse(
    "2,999.95", 
    NumberStyles.Float, 
    (IFormatProvider)culture.GetFormat(typeof(NumberFormatInfo)));

, NumberStyles.Float . Microsoft Connect , - .

Double.Parse NumberStyles.AllowThousands, .

Double.Parse(
    "2,999.95", 
    NumberStyles.Float | NumberStyles.AllowThousands, 
    (IFormatProvider)culture.GetFormat(typeof(NumberFormatInfo)));
+5

Source: https://habr.com/ru/post/1742236/


All Articles