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.142. float.TryParse example
string text = "3.14";
float value;
if (float.TryParse(text, out value))
Console.WriteLine(value);Output:
3.143. Convert.ToFloat example
string text = "3.14";
float value = Convert.ToFloat(text);
Console.WriteLine(value);Output:
3.144. TypeConverter.ConvertFrom example
TypeConverter converter = TypeDescriptor.GetConverter(typeof(float));
string text = "3.14";
float value = (float)converter.ConvertFrom(text);
Console.WriteLine(value);Output:
3.145. Notes
The following methodsfloat.Parse,float.TryParse,Convert.ToFloatandTypeConverter.ConvertFromthrow System.FormatException.