2

.NET looks like it's formatting a double inside a DataRow in the wrong format, so i can't load it in a second moment. If I store "0.000000001", .NET stores it as "1E-09.0", when it should be "1E-09". So Convert.ToDouble("1E-09.0") returns a FormatException. Here it is the code i use:

// create table
DataTable t = new DataTable("test");
t.Columns.Add("FirstInt", typeof(int));
t.Columns.Add("SecondDouble", typeof(double));
t.Columns.Add("ThirdInt", typeof(int));

// create row data
object[] data = new object[] { 10, 0.000000001, 10 };

// add row data: "0.000000001" is stored as "1E-09.0"
t.Rows.Add(data);

// FormatException is thrown here, since "1E-09.0" should be "1E-09"
double d2 = Convert.ToDouble(t.Rows[0]["SecondDouble"]); 

I also tried with cast, but the code throws me "InvalidCastException". The Double.Parse doesn't work as well.

Solution:

// create table
DataTable t = new DataTable("test");
t.Columns.Add("FirstInt", typeof(int));
t.Columns.Add("SecondDouble", typeof(string)); // convert double to string
t.Columns.Add("ThirdInt", typeof(int));

// create row data and convert value to string
double value = 0.0000000001;
string valueString = value.ToString("F9");
object[] data = new object[] { 10, valueString, 10 };
t.Rows.Add(data);

// load data
double d2 = Convert.ToDouble(t.Rows[0]["SecondDouble"]); 
sawk
  • 87
  • 7
  • 1
    How about `double d2 = (double)t.Rows[0]["SecondDouble"];`? – Ulugbek Umirov Apr 15 '14 at 08:06
  • Same. I updated the question to include casting. – sawk Apr 15 '14 at 08:09
  • That sounds strange. Can you show the type of column from your real code? `Console.WriteLine(t.Rows[0]["SecondDouble"].GetType());`. `SecondDouble` column has different type from `double` (most probably `string`). In that case try to find the place where data is added to the table. Or redefine the table column to be of `double` type and change loading method. – Ulugbek Umirov Apr 15 '14 at 08:11
  • I actually did the opposite and it worked: stored double values as string, converting them to F9 format, then loaded. – sawk Apr 15 '14 at 08:21
  • I can't reproduce your issue, and I don't see how the code you posted could produce your issue at all. A DataTable does not store a double value as "1E-09.0"; all it does is boxing it into an object. `1E-09.0` is just a representation, not the actual value of the double. Maybe in your real code there's something else going on? – sloth Apr 15 '14 at 08:26
  • Nope, my code works *exactly* the same. .NET always convert the value 0.000000001 as 1E-09.0, if i specify the column type as double and i store the number with the DataTable.Rows.Add(object[] data) method. Now i forced all columns to have string type. In that way i can manage the double -> string convertion when creating the table and string -> double convertion does not throw the FormatException anymore. – sawk Apr 15 '14 at 08:44

0 Answers0