Parsing floats with Single.TryParse fails

淺唱寂寞╮ 提交于 2019-12-12 21:23:04

问题


There is an article on Single.TryParse over at MSDN with this example code: 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);

Problem is in the article the TryParse returns true and the string is converted, but when I try it, it's false. How do I fix this?


UPD: To simplify parsing, these two lines can be used:

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

This setting allows for negative floats and strings with leading and trailing space characters to be parsed.


回答1:


you need to set culture like this

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

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

or

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
}

Answered over here : C# float.tryparse for French Culture




回答2:


You have problem with your culture about : , character

You can use CultureInvariant in your string



来源:https://stackoverflow.com/questions/12165412/parsing-floats-with-single-tryparse-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!