How to parse string as float in C#?
To parse string as float in C# you can use the built in methodfloat.TryParse()
from using System.Globalization;
namespace. The method will take 4 parameters:1- The string value to be parsed.
2-
NumberStyles.Float
Property.3-
CultureInfo.InvariantCulture
Property.4- out outputValue: which you should define before the parse.
The method
float.TryParse()
will return true
/false
Boolean, it will also return true for an int
number.Remember to include the required namespace:
using System.Globalization;
Example
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
string valueAsString = "0.000456";
float outputValue ;
/* Example Of valid float */
bool success = float.TryParse(valueAsString, NumberStyles.Float , CultureInfo.InvariantCulture , out outputValue );
if(success){
Console.WriteLine("Value is float");
}else{
Console.WriteLine("Value is NOT float");
}
/* Example Of invalid float */
valueAsString = "s";
success = float.TryParse(valueAsString, NumberStyles.Float , CultureInfo.InvariantCulture , out outputValue );
if(success){
Console.WriteLine("Value is float");
}else{
Console.WriteLine("Value is NOT float");
}
}
}
Output
Value is float
Value is NOT float
Value is NOT float