How to Convert string list to float list in C#
By FoxLearn 2/5/2025 9:21:11 AM 3
There are two straightforward ways to do this:
Use List.ConvertAll() with float.Parse()
For example, how to use List.ConvertAll()
with float.Parse()
to convert a list of strings to floats:
var stringList = new List<string>() { "1.1", "2.2", "3.3" }; List<float> floatList = stringList.ConvertAll(float.Parse);
ConvertAll()
loops through each string and applies float.Parse()
to convert each string to a float. The result is a new list containing the parsed floats. This method is generally faster than Select()
for smaller input sizes and somewhat faster for larger input sizes (e.g., greater than 5000 elements).
Use Select() with float.Parse()
For example, using the Linq Select()
method with float.Parse()
to convert a list of strings to a list of floats:
using System.Linq; var stringList = new List<string>() { "1.1", "2.2", "3.3" }; List<float> floatList = stringList.Select(float.Parse).ToList();
The Select()
method returns an IEnumerable<float>
, so you need to call ToList()
to convert the result into a list.
Handling parsing exceptions
When you use float.Parse()
with ConvertAll()
or Select()
, if a string can't be converted, it will throw exceptions. The common exceptions are:
- ArgumentNullException – The string is null.
- FormatException – The string isn’t a valid float (e.g., letters or invalid format).
- OverflowException – The value is greater than
float.MaxValue
or less thanfloat.MinValue
.
To handle these cases, one option is to filter out invalid input. You can do this with float.TryParse()
in a loop, ensuring that only valid parsed numbers are added to the list.
var stringList = new List<string>() { "abc", "1.5", "2.7", "3.4" }; var floatList = new List<float>(stringList.Count); foreach(var s in stringList) { if (float.TryParse(s, out float result)) floatList.Add(result); } Console.WriteLine(string.Join(",", floatList));
This outputs the following valid floats:
1.5,2.7,3.4
If you encounter OverflowExceptions and need to parse larger numbers, consider using a larger type, such as double
or decimal
.
Here's an example of converting to double
using ConvertAll()
:
List<string> stringList = new List<string>() { "1.1", "2.2", "3.3", "1.7976931348623157E+308" // Largest double value }; List<double> doubleList = stringList.ConvertAll(double.Parse);
- String to Byte Array Conversion in C#
- How to Trim a UTF-8 string to the specified number of bytes in C#
- How to Save a list of strings to a file in C#
- How to Convert string list to int list in C#
- How to Remove a list of characters from a string in C#
- How to Check if a string contains any substring from a list in C#
- Find a character in a string in C#
- Remove non-alphanumeric characters from a string in C#