【问题标题】:float.Parse fails on decimals and commasfloat.Parse 在小数和逗号上失败
【发布时间】:2019-02-08 01:41:52
【问题描述】:

当我尝试这条线时:

float f = float.Parse(val, System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands);

其中 val 是设置为“5.267”的字符串,不带引号,我收到此错误:

FormatException:未知字符:。 System.Double.Parse(System.String s,NumberStyles 样式,IFormatProvider 提供程序) System.Single.Parse(System.String s, NumberStyles 样式)

所以我尝试将小数点更改为逗号,例如:5,267 并收到此错误:

FormatException: 未知字符: , System.Double.Parse(System.String s,NumberStyles 样式,IFormatProvider 提供程序) System.Single.Parse(System.String s, NumberStyles 样式)

我....不....明白。据我所知,我这样做是对的。很简单的事情,为什么让我这么难过?

【问题讨论】:

  • 为什么不直接做float.Parse(yourValue);?我刚刚运行它,没有逗号或小数点错误
  • NumberStyles.Any 对我来说很好用,你试过吗?
  • 在您当前的文化中,., 是否都不是小数点或千位分隔符?
  • @TimGoodman 我不知道为什么,但似乎是这样。我和达摩克利斯有同样的问题。当我使用 CurrentCulture 时,它​​不会用小数点解析..

标签: c# parsing


【解决方案1】:

Parse 具有文化意识。如果您的本地文化有不同的要求,那么您可能需要传入文化或其他格式提供程序。尝试使用CultureInfo.InvariantCulture。如果你这样做,你将不需要小数选项。

float f = float.Parse(val,
                      System.Globalization.NumberStyles.AllowThousands,
                      CultureInfo.InvariantCulture);

【讨论】:

  • 就是这样 - 我需要 InvariantCulture。谢谢马特。
  • 这就是我一直在寻找的答案!谢谢!
  • 老兄,如果我用英语编码,我会使用英语“。”小数不是欧洲的','但谢谢你的回答是最好的
  • @Squareroot - 这与您编码的语言无关。它与解释字符串内容的语言有关。您可能正在使用英文关键字和句点编写 C# 来表示文字中的小数,但这并不意味着您的用户一定会说英语。此外,在现实生活中,使用的分隔符不仅与语言有关,还与位置有关。见mathworld.wolfram.com/DecimalPoint.html
【解决方案2】:
using System;
using System.Collections.Generic;
using System.Globalization;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {

            var numList = new List<string>(){"0", "-6e-5", "78.56238", "05.56", "0.5E9", "-45,000.56", "", ".56", "10.4852,64"};
            numList.ForEach(num =>
            {
                // If we use NumberStyles.Float => -45,000.56 is invalid
                if (decimal.TryParse(num, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal result))
                {
                    Console.WriteLine(result);
                }
                else
                {
                    Console.WriteLine(num + " is not a valid number");
                }
            });

        }
    }
}

【讨论】:

  • 尝试更清楚地解释为什么这是问题的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-18
  • 1970-01-01
  • 1970-01-01
  • 2013-10-29
  • 1970-01-01
  • 2021-12-06
  • 2022-01-12
相关资源
最近更新 更多