float.Parse() doesn't work the way I wanted

Dot symbol "." is not used as separator (this depends on Culture settings). So if you want to be absolutely sure that dot is parsed correctly you need to write something like this:

CultureInfo ci = (CultureInfo)CultureInfo.CurrentCulture.Clone();
ci.NumberFormat.CurrencyDecimalSeparator = ".";
avarage = double.Parse("0.0",NumberStyles.Any,ci);

Following works for me:

string stringVal = "0.0";
float floatVal = float.Parse(stringVal , CultureInfo.InvariantCulture.NumberFormat);

The reverse case (works for all countries):

float floatVal = 0.0f;
string stringVal = floatVal.ToString("F1", new CultureInfo("en-US").NumberFormat);

You can check for null or empty string first.

You can also use one of the overloads of Parse (or even use TryParse) to give more specific control.

E.g. to check using the invarient culture, to avoid decimal separator variations with non-user visible data (e.g. from A2A communications):

float SafeParse(string input) {
  if (String.IsNullOrEmpty(input)) { throw new ArgumentNullException("input"); }

  float res;
  if (Single.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out res)) {
    return res;
  }

  return 0.0f; // Or perhaps throw your own exception type
}

Tags:

C#