How to extract decimal number from string in C#

Small improvement to @Michael’s solution:

// NOTES: about the LINQ:
// .Where() == filters the IEnumerable (which the array is)
//     (c=>...) is the lambda for dealing with each element of the array
//     where c is an array element.
// .Trim()  == trims all blank spaces at the start and end of the string
var doubleArray = Regex.Split(sentence, @"[^0-9\.]+")
    .Where(c => c != "." && c.Trim() != "");

Returns:

10.4
20.5
40
1

The original solution was returning

[empty line here]
10.4
20.5
40
1
.

Leave a Comment