如何使用类型转换器转换成具体的双重文化? [英] How to convert culture specific double using TypeConverter?

查看:110
本文介绍了如何使用类型转换器转换成具体的双重文化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与类型转换器类的问题。它的工作原理罚款与 CultureInvariant 值,但不能将特定的文化如英语千位分隔符。下面是一个小的测试程序,我不能去上班。

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.

这里的问题:) - 2,999.95不是双有效值 ConvertFromString 与下面的消息会引发异常的 的并用内部异常的输入字符串的不正确的格式。的。

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);
        }
    }
}

编辑: 链接到<一个bug报告href="https://connect.microsoft.com/VisualStudio/feedback/details/553254/cannot-parse-thousands-separators-using-typeconverter-convertfromstring#details"相对=nofollow>连接

Link to the bug report on Connect

推荐答案

DoubleConverter TypeDescriptor.GetConverter中获得的(typeof运算(双) )结束跌宕调用 Double.Parse 以下参数:

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)));

问题是, NumberStyles.Float 不会让千位分隔符,这就是为什么你所得到的问题。您可以在 Microsoft连接提出这样或看其他人有同样的问题。

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.

如果 Double.Parse 被称为还与 NumberStyles.AllowThousands 不会出现问题。

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)));

这篇关于如何使用类型转换器转换成具体的双重文化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆