In previous article, I mentioned how to Set Default Value to Property in C# but in this article, I have mentioned how we can convert string to float in C# using various possible ways with console application example.
First, I will create a console application in .NET Core, so you can open your Visual Studio 2019/2022 and then create new console application.
Using Float.parse()
Float.parse()
method, converts the string representation of a number to its single-precision floating-point number equivalent.
using System;
using System.Globalization;
namespace StringToFloat
{
internal class Program
{
static void Main(string[] args)
{
var strNumber = "44.5696";
var convertedFloat = float.Parse(strNumber, CultureInfo.InvariantCulture.NumberFormat);
Console.WriteLine(convertedFloat);
}
}
}
Output:
44.5696
Using Convert.ToDouble()
Although, Convert.ToDouble() method is used to convert value to double, but we can still use to convert string to float in C#.
It Converts a specified value to a double-precision floating-point number.
Here is the complete working example using it
using System;
namespace StringToFloat
{
internal class Program
{
static void Main(string[] args)
{
var strNumber = "44.5696";
var convertedFloat = (float) Convert.ToDouble(strNumber);
Console.WriteLine(convertedFloat);
}
}
}
Output:
44.5696
Note: Precision of float number is 7 digits. If you want to keep the more digits after decimal, you need to use the double type which can keep 15-16 digits.
Using Convert.ToSingle()
Convert.ToSingle()
method Converts a specified value to a single-precision floating-point number.
Example:
using System;
namespace StringToFloat
{
internal class Program
{
static void Main(string[] args)
{
var strNumber = "44.5696";
float convertedFloat = Convert.ToSingle(strNumber);
Console.WriteLine(convertedFloat);
}
}
}
Output:
44.5696
That's it, hope this helps.
You may also like to read:
How to convert string to int in C#?C# FromQuery Example in ASP.NET Core API