c# - 使用 Single.TryParse 解析 float 失败

标签 c# floating-point tryparse

MSDN 上有一篇关于 Single.TryParse 的文章,其中包含以下示例代码: http://msdn.microsoft.com/en-us/library/26sxas5t%28v=vs.100%29.aspx

// Parse a floating-point value with a thousands separator.
value = "1,643.57";
if (Single.TryParse(value, out number))
    Console.WriteLine(number);
else
    Console.WriteLine("Unable to parse '{0}'.", value);

文章中的问题是 TryParse 返回 true 并且字符串已转换,但当我尝试它时,它是 false。我该如何解决这个问题?


UPD:为了简化解析,可以使用这两行:

NumberStyles style = System.Globalization.NumberStyles.Any;
CultureInfo culture = CultureInfo.InvariantCulture;

此设置允许解析负 float 和带有前导和尾随空格字符的字符串。

最佳答案

你需要这样设置文化

using System.Globalization;

string value = "1345,978";
NumberStyles style = System.Globalization.NumberStyles.AllowDecimalPoint;
CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR");
if (Single.TryParse(value, style, culture, out number))
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
   Console.WriteLine("Unable to convert '{0}'.", value);

来自msdn:Single.TryParse Method (String, NumberStyles, IFormatProvider, Single%)

float usedAmount;
// try parsing with "fr-FR" first
bool success = float.TryParse(inputUsedAmount.Value,
                              NumberStyles.Float | NumberStyles.AllowThousands,
                              CultureInfo.GetCultureInfo("fr-FR"),
                              out usedAmount);

if (!success)
{
    // parsing with "fr-FR" failed so try parsing with InvariantCulture
    success = float.TryParse(inputUsedAmount.Value,
                             NumberStyles.Float | NumberStyles.AllowThousands,
                             CultureInfo.InvariantCulture,
                             out usedAmount);
}

if (!success)
{
    // parsing failed with both "fr-FR" and InvariantCulture
}

在这里回答:C# float.tryparse for French Culture

关于c# - 使用 Single.TryParse 解析 float 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12165412/

相关文章:

c# - Linq to SQL - 设计问题

c# - Windows 窗体应用程序,自定义控件之间如何通信?

c# - 计算 CPU 使用率

Swift:如何将字节转换为 float /获得更精确的数字?

c# - TryCatch 与 TryParse 的优缺点

c# - IIS 7.5 Windows 2008 R2 远程提供 500,本地提供自定义 404

c++ - 温度将两个 int 数字转换为 float

Python自己改变Float中的Integer

c# - 如何在整行的子字符串上 float.TryParse ?

c# - 多个条件同时tryParse