OneBite.Dev - Coding blog in a bite size

Convert Variable From String To Float In C#

Code snippet for how to Convert Variable From String To Float In C# with sample and detail explanation

Converting variables from one data type to another is a common operation in programming. This short article describes how to convert a variable from string to float in C#.

Code Snippet

string stringVariable = "123.45";
float floatVariable = float.Parse(stringVariable);
Console.WriteLine(floatVariable);

Code Explanation

The above code segment is simple and straightforward, but let’s break it down to elucidate what exactly is happening at each step

  1. string stringVariable = "123.45";: Here we’re declaring a string variable stringVariable, and assigning it the string value "123.45". It’s important to note that although the string contains a numerical value, it is still a string, and cannot be used in mathematical expressions as it stands.

  2. float floatVariable = float.Parse(stringVariable);: Here’s where the actual conversion occurs. float.Parse is a method in C# that’s built specifically to turn numeric strings into float values. What we’re doing is invoking this method, passing stringVariable into it, which then returns the numeric float value of the string.

  3. Console.WriteLine(floatVariable);: Finally, we print the converted float value to the console to verify the conversion was successful. This line of code should output 123.45, but as a floating point number not as a string.

It’s worth noting that if stringVariable contains non-numeric characters, float.Parse(stringVariable) will throw a FormatException. To handle this, you could use the float.TryParse method to try parsing the string, which will return a boolean indicating whether or not the parse was successful, instead of throwing an exception.

With this, you now know how to convert a string to a float in C#. Happy coding!

c-sharp