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

前端 未结 3 1201
悲&欢浪女
悲&欢浪女 2021-01-21 19:27
foreach (object item in listBox1.SelectedItems)
{
    string curItem = item.ToString();
    var parts = curItem.Split(\"{}XY=, \".ToCharArray(), StringSplitOptions.Remov         


        
相关标签:
3条回答
  • 2021-01-21 19:47

    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);
        }
    
    0 讨论(0)
  • 2021-01-21 19:59

    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.

    0 讨论(0)
  • 2021-01-21 20:11

    Consider using regular expressions.

    var match = Regex.Match(val, @"([-+]?[0-9]*\.?[0-9]+)");
    if (match.Success)
      xCoord = Convert.ToSingle(match.Groups[1].Value);
    
    0 讨论(0)
提交回复
热议问题