解析花车与Single.TryParse失败(Parsing floats with Single.

2019-09-21 19:55发布

有上Single.TryParse了一篇文章在MSDN这个例子代码: 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;

此设置允许负花车和首尾的空格字符将被解析字符串。

Answer 1:

你需要设置文化这样

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方法(String,的NumberStyles,的IFormatProvider,单%)

要么

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为法国文化



Answer 2:

你有问题,你对文化:,字符

您可以使用CultureInvariant在你的字符串



文章来源: Parsing floats with Single.TryParse fails