Jenny Mchammer
Jenny Mchammer

Reputation: 95

How can I parse only the float number from the string?

foreach (object item in listBox1.SelectedItems)
{
    string curItem = item.ToString();
    var parts = curItem.Split("{}XY=, ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
    var xCoord = float.Parse(parts[0]);
    var yCoord = float.Parse(parts[1]);
    var point = new PointF(xCoord, yCoord);
    CloudEnteringAlert.pointtocolor.Add(point);
    pictureBox1.Invalidate();
}

The curItem variable contains value like that: Cloud detected at: 0.9174312 Kilometers from the coast.

I want to get only the 0.9174312 from value and set to be in the variable xCoord. The problem is that the way it is doing the parsing now i'm getting error:

Input string was not in a correct format

The index should not be zero, I guess. How can I get only the float number from the string?

And this strings formats for now are the same each time:

First part: Cloud detected at: Second part: 0.9174312 and Last part: Kilometers from the coast.

But maybe in the future I will change the string format so i need that in any place the float number will be in the middle last or start of the string to get only the float number.

Upvotes: 3

Views: 7354

Answers (3)

Srikanth
Srikanth

Reputation: 1010

try this

 foreach (object item in listBox1.SelectedItems)
        {
            string curItem = item.ToString();
            var parts = curItem.Split("{}XY=, ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            var xCoord = CultureCheck(parts[0]);
            var yCoord = CultureCheck(parts[1]);
            var point = new PointF(xCoord, yCoord);
            CloudEnteringAlert.pointtocolor.Add(point);
            pictureBox1.Invalidate();
        }       


    private double CultureCheck(string input)
    {
        CultureInfo ci = (CultureInfo)CultureInfo.CurrentCulture.Clone();
        ci.NumberFormat.CurrencyDecimalSeparator = ".";
       return double.Parse(input, NumberStyles.Any, ci);
    }

Upvotes: 2

Dion V.
Dion V.

Reputation: 2120

You can simply extract the float from the string by using Regular Expressions:

string xCoord = Regex.Match(curItem, @"[-+]?[0-9]*\.?[0-9]+").Groups[1].Value;

After that, you can parse it to a float.

More info about regular expressions can be found here, or you could take a look at the Regex class page from MSDN.

Upvotes: 4

Andrey Korneyev
Andrey Korneyev

Reputation: 26846

Consider using regular expressions.

var match = Regex.Match(val, @"([-+]?[0-9]*\.?[0-9]+)");
if (match.Success)
  xCoord = Convert.ToSingle(match.Groups[1].Value);

Upvotes: 5

Related Questions