Languages
[Edit]
EN

C#/.NET - convert string to float

10 points
Created by:
Kate_C
23510

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 methods float.Parse, float.TryParse, Convert.ToFloat and TypeConverter.ConvertFrom throw System.FormatException.

C# - string conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join