Languages
[Edit]
EN

C#/.NET - convert string to float

10 points
Created by:
Kate_C
2952

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

Hey 👋
Would you like to know what we do?
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.