How to convert culture specific double using TypeConverter?

南楼画角 提交于 2019-12-18 07:03:25

问题


I have a problem with the TypeConverter class. It works fine with CultureInvariant values but cannot convert specific cultures like English thousands separators. Below is a small test program that I cannot get to work.

Here's the problem :) - ConvertFromString throws an exception with the following message "2,999.95 is not a valid value for Double." and with the inner exception "Input string was not in a 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 the bug report on Connect


回答1:


The DoubleConverter that is obtained from TypeDescriptor.GetConverter(typeof(double)) end ups calling Double.Parse with the following arguments:

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

The problem is that NumberStyles.Float does not allows thousands separators and that's why you are getting the problem. You can submit this on Microsoft Connect or see if anybody else had the same problem.

If Double.Parse is called also with NumberStyles.AllowThousands the problem would not occur.

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


来源:https://stackoverflow.com/questions/2688949/how-to-convert-culture-specific-double-using-typeconverter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!