Convert string to double: input string was not in a correct format
12,614
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);
Related videos on Youtube
Author by
Michael
Updated on June 04, 2022Comments
-
Michael almost 2 years
I am getting some values from my Arduino over the serial port. The data has the format:
"value1,value2,value3\r"
as astring
.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; }
-
Sayse over 10 yearsYou've abused Substring quite a lot here, what is wrong with
string.Split(',')
andTryParse
? -
Sergey Berezovskiy over 10 yearsThis code works with your sample data. Please, give data which causes error
-
S_F over 10 yearsSince some people aren't aware of this - the sample data fails on certain regional settings, e.g. Polish uses "," as a decimal point and doesn't consider "4.5" a proper string to convert.
-
Sergey Berezovskiy@user2790895 can you give us value of
data
when you get exception?
-
-
Sergey Berezovskiy over 10 yearsIt should be a comment to question, not an answer to the reason of error
-
Sayse over 10 yearsand it will also probably fail on
0.02\r
-
Sergey Berezovskiy over 10 yearsGood notice on cutting off last character. That probably will be the reason of error
-
S_F over 10 yearsRight, fixed my answer as it does mess with the conversion. Still, CultureInfo setting should be there if the user has a regional setting which doesn't recognize "." as a decimal point.