【问题标题】:1.000.000 is not a valid value for Double c# [duplicate]1.000.000 不是 Double c# 的有效值 [重复]
【发布时间】:2013-01-04 19:29:58
【问题描述】:

可能重复:
How to convert culture specific double using TypeConverter?

尝试使用TypeConverter 将“1.000.000”字符串解析为Double 时出现异常。 我在异常时查看了System.Globalization.NumberFormatInfo,它看起来像这样:

{System.Globalization.NumberFormatInfo}
    CurrencyDecimalDigits: 2
    CurrencyDecimalSeparator: ","
    CurrencyGroupSeparator: "."
    CurrencyGroupSizes: {int[1]}
    CurrencyNegativePattern: 8
    CurrencyPositivePattern: 3
    CurrencySymbol: "TL"
    DigitSubstitution: None
    IsReadOnly: false
    NaNSymbol: "NaN"
    NativeDigits: {string[10]}
    NegativeInfinitySymbol: "-Infinity"
    NegativeSign: "-"
    NumberDecimalDigits: 2
    NumberDecimalSeparator: ","
    NumberGroupSeparator: "."
    NumberGroupSizes: {int[1]}
    NumberNegativePattern: 1
    PercentDecimalDigits: 2
    PercentDecimalSeparator: ","
    PercentGroupSeparator: "."
    PercentGroupSizes: {int[1]}
    PercentNegativePattern: 2
    PercentPositivePattern: 2
    PercentSymbol: "%"
    PerMilleSymbol: "‰"
    PositiveInfinitySymbol: "Infinity"
    PositiveSign: "+"

Everyting 似乎可以解析“1.000.000”,但它说“1.000.000”不是Double 的有效值。问题是什么? 我试图覆盖Thread.CurrentThread.CurrentCulture,但它也不起作用。

已编辑 ::::::::::

这似乎也解决了我的问题。 TypeConverter 实际上可以在没有 ThousandSeperator 的情况下工作。我添加了一个,它开始工作了。

如何使用 TypeConverter 转换特定于文化的双精度的可能重复项? ——拉斯穆斯·法伯 How to convert culture specific double using TypeConverter?

【问题讨论】:

  • 一两个词代表您当前的文化、所需的文化、用于解析字符串的代码以及您如何看待 NumberFormatInfo?
  • 将其发布为一小段完整的代码。
  • 实际上我在 LINQPAD4 上将它做成了一个小型控制台应用程序,它确实有效。但它似乎不适用于大型应用程序本身。还有什么可以看的

标签: c# asp.net .net globalization


【解决方案1】:

试试这个NumberFormatInfo:

var s = "1.000.000";
var info = new NumberFormatInfo
{
    NumberDecimalSeparator = ",", 
    NumberGroupSeparator = "."
};
var d = Convert.ToDouble(s, info);

您可以将NumberDecimalSeparator 更改为其他名称,只要它与NumberGroupSeparator 不同即可。

编辑:您指定的 NumberFormatInfo 也应该可以工作。

【讨论】:

    【解决方案2】:

    Most normal numerical types have parse methods. Use TryParse if you're unsure if it's valid (Trying to parse "xyz" as a number will throw an exception)

    For custom parsing you can define a NumberFormatInfo like this:

    var strInput = "1.000.000";
    var numberFormatInfo = new NumberFormatInfo
    {
        NumberDecimalSeparator = ",",
        NumberGroupSeparator = "."
    };
    double dbl = Double.Parse(strInput, numberFormatInfo);
    

    这个解决方案也可以工作

    var format = new System.Globalization.NumberFormatInfo();
    format.NumberDecimalSeparator = ",";
    format.NumberGroupSeparator = ".";
    double dbl2 = Double.Parse("1.000.000", format);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      • 1970-01-01
      • 2013-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多