I have a text file,which I use to input information into my application.The problem is that some values are float and sometimes they are null,which is why I get an exception.
var s = "0.0";
var f = float.Parse(s);
The code above throws an exception at line 2 "Input string was not in a correct format."
I believe the solution would be the advanced overloads of float.Parse,which include IFormatProvider as a parameter,but I don't know anything about it yet.
How do I parse "0.0"?
The parseFloat() function is used to accept a string and convert it into a floating-point number. If the input string does not contain a numeral value or If the first character of the string is not a number then it returns NaN i.e, not a number.
The float. Parse() method is used to convert given string value to the float value.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With