Question

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.

Was it helpful?

Solution

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

OTHER TIPS

You have problem with your culture about : , character

You can use CultureInvariant in your string

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top