Márk Szombati
Márk Szombati

Reputation: 43

convert string to double not working?

I'd like to convert a string to a double. I know, it has been asked before, but let me finish it! :) So I read the string in from a USB port (Arduino experiment), and I'd like to add that value to a list of doubles. The values are coming in continuously. The problem is, when I try to convert the string to double it gives an error message that says: "The format of the incoming character chain is wrong" or something like this. I get this error message with both the parse and convert command. What should I do?

Here's the part of the code that supposed to do the job:

namespace voltmeres{
public partial class Form1 : Form
{
    List<double> lista = new List<double>();
    int i;
    double f;
    string POT;
    public Form1()
    {
        InitializeComponent();
        serialPort1.PortName = "COM5";
        serialPort1.BaudRate = 9600;
        lista.Capacity = 100;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (serialPort1.IsOpen)
        {
            POT =serialPort1.ReadExisting();
                textBox1.Text = POT.ToString();
        }
        f = Convert.ToDouble(textBox1.Text);
        lista.Add(f);
        i++;
        if (i == lista.Capacity)
        {
            lista.Capacity=lista.Capacity + 100;
        }
    }

Upvotes: 3

Views: 3564

Answers (4)

Ankush Madankar
Ankush Madankar

Reputation: 3834

Try this

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (serialPort1.IsOpen)
        {
            POT = serialPort1.ReadExisting();
            textBox1.Text = POT.ToString();
        }

        if (! double.TryParse(textBox1.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out f)) return;

        f = Convert.ToDouble(textBox1.Text);
        lista.Add(f);
        i++;
        if (i == lista.Capacity)
        {
            lista.Capacity = lista.Capacity + 100;
        }
    }

Upvotes: 2

Phylogenesis
Phylogenesis

Reputation: 7880

From the comments, it looks like it's a number formatting issue. Try the following:

f = Convert.ToDouble(textBox1.Text, new System.Globalization.CultureInfo("en-US"));

Upvotes: 2

Devious
Devious

Reputation: 96

If the above answers don't work, try 'String.valueOf(your double);' This should do the trick if your double is correct.

Another suggestion : depending on the double you have, for instance if it is a really long double, you may want to format the value before or after the conversion to take only a few digits.

Upvotes: 0

Ehsan
Ehsan

Reputation: 32651

You should use double.TryParse instead. It will parse if it is a double, else it will not throw an exception.

if(double.TryParse(textBox1.Text,outf))
{
   lista.Add(f);
    i++;
    if (i == lista.Capacity)
    {
        lista.Capacity=lista.Capacity + 100;
    }
}

Upvotes: 0

Related Questions