Mohanapriya R Mohanapriya R
Updated date Apr 03, 2024
In this article, we will learn how to convert strings to floats in C#. Explore the float.Parse() and float.TryParse() methods.
  • 2.3k
  • 0
  • 0

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}");
    }
}

Output:

Using float.Parse(): 3.14
Using float.TryParse(): 3.14

In this program, we use 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.

Comments (0)

There are no comments. Be the first to comment!!!