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