[Solved] C# float.tryparse for French Culture

I have a user input which can contain float values ranging from : 3.06 OR 3,06
The culture we are in is French and thus when the user inputs 3.06 and I run a float.tryParse over this value it does not get converted to 3.06 into a new variable (type float)

// inputUsedAmount.Value from UI is : 3.06
float usedAmount = 0.0f;
float.TryParse(inputUsedAmount.Value, out usedAmount);
// returns false

I can simply do a replace on the amount entered from UI from “.” to “,”, but is there a graceful/better way of doing this through Culture ?

Solution #1:

You can use the overload that takes a format provider. You can pass through a French culture info:

string value;
NumberStyles style;
CultureInfo culture;
double number;

value = "1345,978";
style = NumberStyles.AllowDecimalPoint;
culture = CultureInfo.CreateSpecificCulture("fr-FR");
if (Double.TryParse(value, style, culture, out number))
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
   Console.WriteLine("Unable to convert '{0}'.", value);
// Displays:
//       Converted '1345,978' to 1345.978.
Respondent: Oded

Solution #2:

float usedAmount;

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

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

if (!success)
    // parsing failed with both "fr-FR" and InvariantCulture
Respondent: LukeH

Solution #3:

You can pass culture inside TryParse method:

public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out float result);
Respondent: Andrew Bezzub

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.