Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So What I need help is to Fix a float error. This is a Program that receive Data from Serial Port and will do some stuff if starts with "+", that is coming from a Balance. Here is the code. Sorry if is in Portuguese. If got some daught please contact, I respond in minutes

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



namespace TesteSerial
{
    public partial class frmPrincipal : MetroForm
    {
        List<float> weights = new List<float>();


        public frmPrincipal()
        {
            InitializeComponent();
            CarregarImpressoras();

            //ComboBox Opcoes BaudRate
            cboBaudRate.Items.Add("75");
            cboBaudRate.Items.Add("110");
            cboBaudRate.Items.Add("300");
            cboBaudRate.Items.Add("1200");
            cboBaudRate.Items.Add("2400");
            cboBaudRate.Items.Add("4800");
            cboBaudRate.Items.Add("9600");
            cboBaudRate.Items.Add("19200");
            cboBaudRate.Items.Add("38400");
            cboBaudRate.Items.Add("57600");
            cboBaudRate.Items.Add("115200");
        }

        private void frmPrincipal_Load(object sender, System.EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();
            cboPortaCom.Sorted = true;
            foreach (var s in ports)
            {
                cboPortaCom.Items.Add(s);
            }
            if (cboPortaCom.Items.Count > 0)
            {
                cboPortaCom.SelectedIndex = 0;
            }
        }
        [System.ComponentModel.Bindable(true)]
        [System.ComponentModel.Browsable(false)]
        public object SelectedItem { get; set; }

        private const string textPrefix = @"+";
        private const string prefixmenos = @"-";

        private void btnteste_Click(object sender, EventArgs e) // Button for send Data in txtDadosRecebidos
        {
            txtDadosRecebidos.Text += "+   0.089";

            if (txtDadosRecebidos.Text.StartsWith(textPrefix))
            {
                string input = txtDadosRecebidos.Text; // this is your input, replace that with your variable where the text comes from
                string inputWithoutNewline = input.Remove(input.Length - 1, 1); // removes last character, is now: "+ 9.81"
                string inputWithoutSpace = inputWithoutNewline.Replace(" ", ""); // this replaces all spaces with nothing (aka removes the one after the +), is now "+9.81"
                string inputWithoutPoint = inputWithoutSpace.Replace(".", ","); // Trying to change "," to "."

                Console.WriteLine(txtDadosRecebidos.Text);
             //   float parsedFloat = float.Parse(inputWithoutSpace); // this converts the string into an actual float
            }
            else
                {
                txtDadosRecebidos.Text = metroTextBox1.Text;
                }
        }
        private void btnAbrirPorta_Click(object sender, System.EventArgs e) // Opening / Closing COM Port 
        {
          

            if (cboBaudRate.SelectedItem != null)
            {
                int selectedIndex = cboBaudRate.SelectedIndex;
                Object selectedItem = cboBaudRate.SelectedItem;

                string BaudRate = cboBaudRate.SelectedItem.ToString();

                float parsedFloat = float.Parse(BaudRate); // this converts the string into an actual float

                int parsedInt = int.Parse(BaudRate);

                if (spComunica.IsOpen)
                {
                    btnAbrirPorta.BackColor = Color.LightGreen;
                    btnAbrirPorta.Text = "Abrir";
                    spComunica.Close();
                }
                else
                {
                    btnAbrirPorta.BackColor = Color.Red;
                    btnAbrirPorta.Text = "Fechar";
                    spComunica.PortName = cboPortaCom.Text;
                    spComunica.BaudRate = parsedInt;
                    Console.WriteLine(cboBaudRate.SelectedItem);
                    spComunica.Open();
                }
                btnEnviar.Enabled = txtEnviaDado.Enabled = spComunica.IsOpen;
            }
            else
            {
                MessageBox.Show("Selecione um Baud Rate");
            }
        }

        private void btnEnviar_Click(object sender, System.EventArgs e) // Send Data for Com Port
        {
            spComunica.Write(txtEnviaDado.Text);
        }
        private void spComunica_DataReceived(object sender, SerialDataReceivedEventArgs e) // Receive Data from COM Port and starts working
        {
            string input = "";
            try
            {
                input = spComunica.ReadExisting();
            }
            catch (InvalidOperationException)
            {
                return;
            }

            if (input.StartsWith(textPrefix)) // IF start with "+", that is how Weight Come from Balance, will treat and put correctly for convert to float ( Remove Spaces and that stuff))
            {
                txtDadosRecebidos.BackColor = Color.LightGreen;
                string inputWithoutNewline = input.Remove(input.Length - 1, 1); // removes last character, is now: "+ 9.81"
                string inputWithoutSpace = inputWithoutNewline.Replace(" ", ""); // this replaces all spaces with nothing (aka removes the one after the +), is now "+9.81"
                string inputWithoutPoint = inputWithoutSpace.Replace(".", ","); // Trying to change "," to "."
                BeginInvoke((MethodInvoker)(() => { txtDadosRecebidos.Text = inputWithoutPoint; }));
                Console.WriteLine(inputWithoutPoint);
                float parsedFloat = float.Parse(inputWithoutPoint); // this converts the string into an actual float ---> HERE IS THE ERROR WHEN I Open connection

                weights.Add(parsedFloat);

                if (weights.Count >= 5) // What I need to catch 5 weights, if they are the same that means that the balace is estabilized, so It will send Weight to left txtBox 
                {
                    float average = (weights[0] + weights[1] + weights[2] + weights[3] + weights[4]) / 5;
                    if (Math.Abs(average - weights[0]) < 0.02) ;
                    {
                        string avgString = average + "KG \n";
                        BeginInvoke((MethodInvoker)(() => { metroTextBox1.Text = avgString; }));
                        weights.Clear();
                    }
                }
                else
                {
                    weights.RemoveAt(0);
                    return;

                }
            }

            else if (input.StartsWith(prefixmenos))
            {
                txtDadosRecebidos.BackColor = Color.Red;
                string inputWithoutNewline = input.Remove(input.Length - 1, 1); // removes last character, is now: "+ 9.81"
                string inputWithoutSpace = inputWithoutNewline.Replace(" ", ""); // this replaces all spaces with nothing (aka removes the one after the +), is now "+9.81"
                string inputWithoutPoint = inputWithoutSpace.Replace(".", ","); // Trying to change "," to "."
                BeginInvoke((MethodInvoker)(() => { txtDadosRecebidos.Text = inputWithoutPoint; }));
                 Console.WriteLine(inputWithoutPoint);
                float parsedFloat = float.Parse(inputWithoutPoint); // this converts the string into an actual float ---> HERE IS ALSO THE ERROR WHEN I Open connection
            }
        }
        private void btSair_Click(object sender, System.EventArgs e)
        {
            Application.Exit();
        }

        private void btenviardb_Click(object sender, System.EventArgs e)
        {
            try
            {
                //This is my connection string i have assigned the database file address path  
                string connetionString = "server=localhost;database=codbarras;uid=root;pwd=;";
                //This is my insert query in which i am taking input from the user through windows forms  
                string Query = "insert into codigobarras values('" + this.metroTextBox1.Text + "');";
                //This is  MySqlConnection here i have created the object and pass my connection string.  
                MySqlConnection MyConn2 = new MySqlConnection(connetionString);
                //This is command class which will handle the query and connection object.  
                MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
                MySqlDataReader MyReader2;
                MyConn2.Open();
                MyReader2 = MyCommand2.ExecuteReader();     // Here our query will be executed and data saved into the database.  
                MessageBox.Show("Dados Guardados!");
                while (MyReader2.Read())
                {
                }
                MyConn2.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //botão imprimir 
        private void btImprimir_Click(object sender, System.EventArgs e)
        {
            using (var pd = new System.Drawing.Printing.PrintDocument())
            {
                pd.PrinterSettings.PrinterName = impressoraComboBox.SelectedItem.ToString();
                pd.Print();
            }
        }
        private void CarregarImpressoras()
        {
            impressoraComboBox.Items.Clear();

            foreach (var impressora in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
            {
                impressoraComboBox.Items.Add(impressora);
            }
        }

        private void cboBaudRate_SelectedIndexChanged(object sender, EventArgs e)
        {


        }
        private void txtDadosRecebidos_Click(object sender, EventArgs e)
        {
            {

            }
        }
        private void bt1_Click(object sender, EventArgs e)
        {
        }

        private void btenviardbPeso_Click(object sender, EventArgs e)
        {
            try
            {
                //This is my connection string i have assigned the database file address path  
                string connetionString = "server=localhost;database=codbarras;uid=root;pwd=;";
                //This is my insert query in which i am taking input from the user through windows forms  
                string Query = "insert into pesobalanca values('" + this.metroTextBox1.Text + "');";
                //This is  MySqlConnection here i have created the object and pass my connection string.  
                MySqlConnection MyConn2 = new MySqlConnection(connetionString);
                //This is command class which will handle the query and connection object.  
                MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
                MySqlDataReader MyReader2;
                MyConn2.Open();
                MyReader2 = MyCommand2.ExecuteReader();     // Here our query will be executed and data saved into the database.  
                MessageBox.Show("Dados Guardados!");
                while (MyReader2.Read())
                {
                }
                MyConn2.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void metroTextBox1_Click(object sender, EventArgs e)
        {
        }
        private void btLimpar_Click(object sender, System.EventArgs e)
        {
            txtDadosRecebidos.Clear();
        }

        private void limparRegisto_Click(object sender, EventArgs e)
        {
            metroTextBox1.Clear();
        }
    }
}


What I have tried:

float parsedFloat = float.Parse(inputWithoutPoint); // this converts the string into an actual float ---> HERE IS THE ERROR WHEN I Open connection, says " 
Incorrectly formatted input string. "
Posted
Updated 28-Apr-22 3:05am
Comments
Richard Deeming 28-Apr-22 5:07am    
The error suggests that the value of inputWithoutPoint is not a valid string representation of a floating-point number in the current culture your code is running under.

You need to debug your code to see what the variable contains, and what culture the code is using.

We can't do that for you.
Member 15594108 28-Apr-22 5:22am    
I already see what comes from the data after get transormed ( inputWithoutPoint ), and at console is "+0,00" or other value like this. I think the data is already ready to be transformed to float. I just don't know why gives error.
Richard Deeming 28-Apr-22 5:33am    
That appears to be using a comma (,) rather than a period (.) as the decimal separator.

You need to double-check the culture your code is running under.
Phil J Pearson 28-Apr-22 5:34am    
+0,00 is not a valid float representation in the invariant culture. The decimal separator needs to be .
Make sure that the culture you use for parsing matches the culture of the incoming string.
Member 15594108 28-Apr-22 5:50am    
I tried also, I put "string inputWithoutPoint = inputWithoutSpace.Replace(",", ".");" // Trying to change "," to "." and don't wokr. on Output Console appear like "+0.131" and still error at float

1 solution

Here's an idea. I leave it to you to implement it in your code as appropriate. I use string extension methods to perform the "work". If you're not familiar with extension methods, google is your friend. I also implemented some rudimentary sanity checks to avoid unneccesary processing.

C#
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            TestFloatStringParse(true);
            Console.Write("Press any key...");
            Console.ReadKey();
        }

        /// <summary>
        /// Method to test parsing out numeric values 
        /// </summary>
        /// <param name="makeIntsFloats">If true, converts any resulting integers 
        /// to floating point values by adding ".0"</param>
        private static void TestFloatStringParse(bool makeIntsFloats = false)
        {
            // our original string, exercising a number of combinations of characters
            string text = "+0.1 + 1.78 * 27.5/ (5+    0)A;";
            Console.WriteLine(string.Concat("original string = ", text));

            // call our string extension method, and display the new string that has 
            // spaces where the non-numeric characters were
            text = text.ReplaceNonNumeric(' ');
            Console.WriteLine(string.Concat("new string = ", text));

            if (makeIntsFloats)
            {
                // optional - add decimal to values that appear to be integers
                string[] parts = text.Split(' ');
                for (int i = 0; i < parts.Length; i++)
                {
                    parts[i] = (parts[i].Contains('.')) ? parts[i] : string.Concat(parts[i], ".0");
                }

                text = string.Empty;
                foreach (string part in parts)
                {
                    text = string.Concat(text, part, " ");
                }
                text = text.Trim();
            }

            Console.WriteLine(string.Concat("optional string = ", text));
        }
    }

    /// <summary>
    /// Extension class for strings that peforms culture-specific replacement of non-numeric 
    /// characters in a given string.
    /// </summary>
    public static class ExtendStrings
    {
        // determine culture-specific numeric values (including separators)
        private static NumberFormatInfo nfi = CultureInfo.InvariantCulture.NumberFormat;
        private static string numerics = string.Join("", nfi.NativeDigits);
        private static string separators = string.Concat(nfi.CurrencyDecimalSeparator,
                                                         nfi.CurrencyGroupSeparator,
                                                         nfi.NumberDecimalSeparator,
                                                         nfi.NumberGroupSeparator,
                                                         nfi.PercentDecimalSeparator,
                                                         nfi.PercentGroupSeparator);

        /// <summary>
        /// Replace all non-numeric characters with the specified character
        /// </summary>
        /// <param name="text"></param>
        /// <param name="replacement"></param>
        /// <returns></returns>
        public static string ReplaceNonNumeric(this string text, char replacement)
        {
            string result = text;

            // if the replacement char is not null, we have work to do
            if (replacement != (char)0)
            {
                if (string.Concat(numerics, separators).Contains(replacement))
                {
                    throw new InvalidOperationException("Replacement characters cannot include culture-specific numeric values or separators");
                }

                // replace non-numeric chars with the specified string
                result = text.ReplaceNonNumeric(replacement.ToString());
            }

            return result;
        }

        /// <summary>
        /// Replace all non-numeric chars with a specified replacement 
        /// </summary>
        /// <param name="text">This text</param>
        /// <param name="replacement">The replacement string</param>
        /// <returns></returns>
        public static string ReplaceNonNumeric(this string text, string replacement)
        {
            string result = text;
            // sanity checks to make sure we have replacement string as well as a string 
            // to work on
            if (!string.IsNullOrEmpty(replacement) && !string.IsNullOrEmpty(text))
            {
                result = string.Empty;
                foreach (char ch in text)
                {
                    result = string.Concat(result, (ch.IsNumeric()) ? ch : ' ');
                }

                // replace all instances of subsequent multiple replacement strings until 
                // each value is separated by only a single instance of the replacement
                result = (replacement.Length == 1) ? result.ReplaceDuplicateSequentialChars(replacement[0]) : result;
                result = result.Trim();
            }
            return result;
        }

        /// <summary>
        /// Determine if the character is numeric according to culture-specific values
        /// </summary>
        /// <param name="ch"></param>
        /// <returns></returns>
        public static bool IsNumeric(this char ch)
        {
            bool result = (numerics.Contains(ch) || separators.Contains(ch));
            return result;
        }

        /// <summary>
        /// Converts any instance of multiple subsequent occurrences of the specified character 
        /// with a single instance of that character. This is only performed when the replacement 
        /// is aa single character, or a single character string.
        /// </summary>
        /// <param name="text"></param>
        /// <param name="ch"></param>
        /// <returns></returns>
        public static string ReplaceDuplicateSequentialChars(this string text, char ch)
        {
            string result = text;
            int length = 0;
            while (true)
            {
                length = result.Length;
                result = result.Replace("  ", " ");
                if (length == result.Length)
                {
                    break;
                }
            }
            return result;
        }
    }
}
 
Share this answer
 
Comments
Member 15594108 29-Apr-22 5:44am    
private void spComunica_DataReceived(object sender, SerialDataReceivedEventArgs e) // Receive Data from COM Port and starts working
{
string input = "";
try
{
input = spComunica.ReadExisting();
Console.WriteLine(input);

}
catch (InvalidOperationException)
{
return;
}

if (input.StartsWith(textPrefix)) // IF start with "+", that is how Weight Come from Balance, will treat and put correctly for convert to float ( Remove Spaces and that stuff))
{
txtDadosRecebidos.BackColor = Color.LightGreen;
string inputWithoutNewline = input.Remove(input.Length - 1, 1); // removes last character, is now: "+ 9.81"
string inputWithoutSpace = inputWithoutNewline.Replace("\n", "").Replace(" ", ""); ; // this replaces all spaces with nothing (aka removes the one after the +), is now "+9.81"
string inputWithoutPoint = inputWithoutSpace.Replace("+", ""); // Trying to change "," to "."

//Console.WriteLine(inputWithoutPoint);

foreach (string line in new LineReader(() => new StringReader(input)))
{
if (line.Contains(".") && line.StartsWith(textPrefix))
{
string inputWithoutNewline2 = line.Remove(line.Length - 1, 1);
string inputWithoutDot = inputWithoutNewline2.Replace(".", ",");
string originalFloatString = inputWithoutDot.Remove(0, textPrefix.Length + 2);
Console.WriteLine("1...." + inputWithoutNewline2);
Console.WriteLine("2...." + originalFloatString);
float weightFloat = float.Parse(originalFloatString);
weights.Add(weightFloat);
}
}

string fetchedWeights = "";

foreach (float weight in weights)
{
fetchedWeights = fetchedWeights + weight.ToString() + "\n";
}

BeginInvoke((MethodInvoker)(() => { txtDadosRecebidos.Text = fetchedWeights; }));
}

}

I already put the code like this and is working the only problem is that the weight is not getting updated. It just register the 1st weight and not others. Like the transformation of the text only happends for the first one. I need to every time that Data starts with "+" transform transform in float and send to txtbox ( txtDadosRecebidos ) to get always updated

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900