. Advertisement .
..3..
. Advertisement .
..4..
You can convert a string to float in C# by using the TryParse or Parse method or calling the System.Convert class. Read on to find out what is the main difference between them.
Convert A String To Float In C#
String To Number Conversion In C#
In general, the Parse and TryParse methods can be slightly more straightforward and efficient. In fact, many methods of the Convert class, such as Convert.ToInt32
, use Parse internally.
However, the Convert class has its use too. This option can be more useful when you need to deal with objects that have the IConvertible interface.
With Parse() and TryParse()
The methods TryParse or Parse can be used on numeric types like float if you expect the original string contains it. It is important to note that in C#float is the keyword reserved for System.Single (or single-precision floating-point numbers) in .NET.
While the Parse method simply returns the float value it has converted from the string you provide, TryParse works in a different way. This method returns two values: one boolean showing whether it has succeeded in carrying out the conversion, and the out parameter is the converted float.
Note: C# allows you to pass a function as a parameter as well. Want to know how? Head to this guide.
This difference also leads to different outcomes when C# fails to convert your string to a float. When your string doesn’t contain a valid float, or for some reason, it can’t be converted to float successfully, the Parse method invokes an exception, and TryParse just returns false. If you want to handle errors when the operation fails, you should use exceptions (FormatException in particular).
This is a simple example of using Parse()
and TryParse()
:
using System;
class Example
{
static void Main(string[] args) {
string myStr = "3.14159";
try {
float myFlt1 = float.Parse(myStr);
Console.WriteLine(myFlt1);
}
catch (FormatException e) {
Console.WriteLine(e.Message);
}
if (float.TryParse(myStr, out float myFlt2)) {
Console.WriteLine(myFlt2);
}
}
}
Output:
3.14159
3.14159
As you can see, both methods return the same value that we are expecting. We add an exception handle with Parse()
to catch any possible FormatException. There is no need to do that with TryParse. An if statement should be enough to invoke the suitable code block while still being able to throw an error message when the operation fails.
Remember that Parse()
and TryParse()
ignore white space at the beginning and the end of strings. Other characters, however, must be able to form a valid float value. Strings like String.Empty
or ones with the null value won’t parse successfully. You can use the String.IsNullOrEmpty
method to check if a string is null or empty before calling Parse()
or TryParse()
.
With Convert.ToSingle()
The Convert class comes with the ToSingle method that you can use to convert a string to a float.
public static float ToSingle (string? value);
The method will return a single-precision floating-point number equivalent to the float in value. Like Parse()
, you will need to write a custom exception handler to deal with errors.
Example:
using System;
class Example
{
static void Main(string[] args) {
string[] values= { "3.14159", "ABCD"};
float result;
foreach (string value in values)
{
try {
result = Convert.ToSingle(value);
Console.WriteLine("Converted '{0}' to {1}",
value,
result);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}' to a Single.", value);
}
}
}}
Output:
Converted '3.14159' to 3.14159
Unable to convert 'ABCD' to a Single.
The program shows that Convert.ToSingle
can also only make the conversion with strings that contain valid float values.
Conclusion
You can easily convert a string to float in C# with Parse()
, TryParse()
, or Convert.ToSingle()
. They all come from the System namespace and work in different ways, allowing you to adapt them to various applications.
Leave a comment