Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to double: input string was not in a correct format

I am getting some values from my Arduino over the serial port. The data has the format: "value1,value2,value3\r" as a string.

Example: "4.5,550.0,0.02\r"

I can recieve and separate the values but when I try to convert them to double I get the following exception

"input string was not in a correct format"`.

double Battery = 0, Voltage = 0, Current = 0;

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    string data = serialPort1.ReadLine();
    string bv = data.Substring(0, data.IndexOf(",") - 1);
    data = data.Substring(data.IndexOf(",") + 1);
    string v0 = data.Substring(0, data.IndexOf(",") - 1);
    data = data.Substring(data.IndexOf(",") + 1);
    string i = data;

    double batteryVoltage = Convert.ToDouble(bv);
    double V0 = Convert.ToDouble(v0);
    double I = Convert.ToDouble(i);

    Battery = batteryVoltage;
    Voltage = V0;
    Current = I;

}
like image 592
Michael Avatar asked Sep 18 '13 09:09

Michael


1 Answers

Two things are a problem here. First, the conversion may fail because of regional settings (invalid decimal point character), so use CultureInfo.InvariantCulture from System.Globalization namespace as an additional parameter. Second thing, you are cutting off one character from your substrings, so remove -1.

string data = "4.5,550.0,0.02\r";
string bv = data.Substring(0, data.IndexOf(","));
data = data.Substring(data.IndexOf(",") + 1);
string v0 = data.Substring(0, data.IndexOf(","));
data = data.Substring(data.IndexOf(",") + 1);
string i = data;

double batteryVoltage = Convert.ToDouble(bv, CultureInfo.InvariantCulture);
double V0 = Convert.ToDouble(v0, CultureInfo.InvariantCulture);
double I = Convert.ToDouble(i, CultureInfo.InvariantCulture);
like image 102
S_F Avatar answered Sep 22 '22 00:09

S_F