EN
C#/.NET - convert string to float
10
points
In C#/.NET string can be parsed to float in few ways.
1. float.Parse
example
string text = "3.14";
float value = float.Parse(text);
Console.WriteLine(value);
Output:
3.14
2. float.TryParse
example
string text = "3.14";
float value;
if (float.TryParse(text, out value))
Console.WriteLine(value);
Output:
3.14
3. Convert.ToFloat
example
string text = "3.14";
float value = Convert.ToFloat(text);
Console.WriteLine(value);
Output:
3.14
4. TypeConverter.ConvertFrom
example
TypeConverter converter = TypeDescriptor.GetConverter(typeof(float));
string text = "3.14";
float value = (float)converter.ConvertFrom(text);
Console.WriteLine(value);
Output:
3.14
5. Notes
The following methodsfloat.Parse
,float.TryParse
,Convert.ToFloat
andTypeConverter.ConvertFrom
throw System.FormatException.