How to Convert Strings to Floats using C#
In C#, the float.Parse()
and float.TryParse()
methods are commonly used to convert strings to float values. The float.Parse()
method converts a string representation of a number to its floating-point equivalent, but it may throw an exception if the conversion fails. On the other hand, float.TryParse()
returns a boolean value, indicating whether the conversion was successful or not, without throwing an exception.
using System;
class Program
{
static void Main()
{
// Input string
string inputString = "3.14";
// Using float.Parse()
try
{
float parsedFloat = float.Parse(inputString);
Console.WriteLine($"Using float.Parse(): {parsedFloat}");
}
catch (FormatException)
{
Console.WriteLine("Invalid format for float.Parse()");
}
// Using float.TryParse()
float.TryParse(inputString, out float tryParsedFloat);
Console.WriteLine($"Using float.TryParse(): {tryParsedFloat}");
}
}
We used both float.Parse()
and float.TryParse()
to convert the string "3.14" to a float. The float.Parse()
method successfully converts the string, while float.TryParse()
does the same without raising an exception.
Output:
Using float.Parse(): 3.14
Using float.TryParse(): 3.14
Comments (0)