C# 分析浮点字符串中的整数

C# 分析浮点字符串中的整数,c#,.net,windows,arrays,string,C#,.net,Windows,Arrays,String,我已设法通过RS232从温度传感器获取值。预期值将添加到数据库中,以便进一步操作。这是代码 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using MySql.Data.MySqlClient; using Sys

我已设法通过RS232从温度传感器获取值。预期值将添加到数据库中,以便进一步操作。这是代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO.Ports;

namespace SimpleSerial
{

    public partial class Form1 : Form
    {
        // Add this variable 
        MySqlConnection conn = null;
        float tempvalue;
        string RxString;

        public Form1()
        {
            InitializeComponent();
        }
        public void dbconnect()
        {
            string cs = @"server=xxx.x.x.xx;userid=uuuuuu;password=xxxxx;database=project";
            try
            {
                conn = new MySqlConnection(cs);
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = "INSERT INTO temp(value) VALUES(@value) ";
                cmd.Prepare();
                cmd.Parameters.AddWithValue("@value", tempvalue);
                cmd.ExecuteNonQuery();
                //Console.WriteLine("MySQL version : {0}", conn.ServerVersion);

                //MessageBox.Show("DB Connected");
            }
            catch (MySqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
                MessageBox.Show("Error: {0}", ex.ToString());
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }

        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            serialPort1.PortName = "COM2";
            serialPort1.BaudRate = 9600;
            serialPort1.Open();
            if (serialPort1.IsOpen)
            {
                buttonStart.Enabled = false;
                buttonStop.Enabled = true;
                textBox1.ReadOnly = false;
            }

        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
                buttonStart.Enabled = true;
                buttonStop.Enabled = false;
                textBox1.ReadOnly = true;
            }

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (serialPort1.IsOpen) serialPort1.Close();
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            // If the port is closed, don't try to send a character.
            if (!serialPort1.IsOpen) return;

            // If the port is Open, declare a char[] array with one element.
            char[] buff = new char[1];

            // Load element 0 with the key character.
            buff[0] = e.KeyChar;

            // Send the one character buffer.
            serialPort1.Write(buff, 0, 1);

            // Set the KeyPress event as handled so the character won't
            // display locally. If you want it to display, omit the next line.
            e.Handled = true;
        }

        private void DisplayText(object sender, EventArgs e)
        {
            tempvalue = float.Parse(RxString);    
            dbconnect();
            textBox1.AppendText(RxString);
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            RxString = serialPort1.ReadExisting();
            this.Invoke(new EventHandler(DisplayText));

        }
    }
}
请注意:

    tempvalue = float.Parse(RxString);    
    dbconnect();
    textBox1.AppendText(RxString);
是我想要操纵的值。电流输出类似于56.1234557.4323253.34221。感兴趣的值是每个“.”后面左边的两个数字。我想得到这个值有56 57 53等。我试过四舍五入,它似乎不是这里的最佳选择。由于它来自串行端口,读取值的方式使我丢失了一些位。 有没有办法将XX.ddd中的Xs和Ds分开,并使用XX填充数据库?我尝试了
RxString.Split('.')
。也许我做得不对。有人好心帮忙。谢谢

string[] values = RxString.Split(new Char[] {','}); 
foreach(String value in values)
{
   string[] parts = value.Split(new char[] {'.'});
   if (parts.Length == 2)
   {
      int v;
      if (int.TryParse(parts[0], out v))
      {
          // do something with v
      }
   }
}

如果我明白了。

您可以使用正则表达式提取字符串的有趣部分

MatchCollection matches =
    Regex.Matches("56.1234557.4323253.34221", @"\d\d(?=\.)");
foreach (Match match in matches) {
    Console.WriteLine(match.Value);
}

我使用了正则表达式模式
find(?=后缀)
,它匹配后缀前面的位置
\d\d
匹配两位数字,
\。
匹配小数点。

string result=RxString.Split(“.”);由于它不更改字符串,因此返回一个新字符串:)要尝试类似Split().First()的操作。但是RxString有一个错误。这是一个数组,因此函数不适用。您可能不应该在此处显示连接字符串和密码。有趣。也是一个好选项。非常感谢!