如何仅解析字符串中的浮点数? [英] How can I parse only the float number from the string?

查看:40
本文介绍了如何仅解析字符串中的浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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();
}

curItem变量包含的值如下:在距海岸0.9174312公里处检测到的云.

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

我只想从值中获取 0.9174312 并将其设置为变量xCoord.问题是它现在进行解析的方式出现错误:

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:

输入字符串的格式不正确

我猜索引应该不为零.如何仅从字符串中获取浮点数?

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:

第一部分: 在以下位置检测到的云:第二部分:0.9174312和最后一部分:距海岸的距离.

但是也许将来我会更改字符串格式,所以我需要在任何地方浮点数都在字符串的最后或中间,以仅获取浮点数.

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.

推荐答案

考虑使用正则表达式.

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

这篇关于如何仅解析字符串中的浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆