1

I have a MySQL database with the table "Products". A column in "Products" is called "Price" and has the datatype "double".

I need to retrieve the values from that column, so I create a reader, etc.:

MySQLCommand cmd = new MySQLCommand("SELECT Price FROM Products", connection);
MySQLDataReader reader = cmd.ExecuteReaderEx();

if (reader.HasRows == true)
{
  while (reader.Read() == true)
  {
    price = reader["Price"]).ToString();
  }
}

Problem is that price isn't set to the expected value. If the value in the database is "299.95", price is set to "29995.0".

Any idea why this is happening? And what can be done to fix it?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Louisa
  • 552
  • 1
  • 9
  • 22

2 Answers2

3

This is, because toString() uses the current CultureInfo! It depends on the culture if a double is separated by a comma or a dot.

CultureInfo

See also this Stackoverflow Question!

If you debug it you should see, that reader["Price"] is returning an Object (type=Object{double}). Is here the value correct? I guess it is, so just make following to display the double-value:

string display = double.Parse(reader["Price"], CultureInfo.InvariantCulture).ToSring(CultureInfo.CurrentCulture);
System.Diagnostics.Debug.WriteLine(display);
Community
  • 1
  • 1
harry
  • 672
  • 3
  • 13
  • Sounds resonable, but reader["Price"] returns "29995.0". So it looks like it is already to late to try to make it understand that "." should be interpreted as ",". – Louisa Jan 03 '13 at 12:02
  • What happens if you try to parse it in a double?? double test = (double) reader["Price"] Is this working?? If not, I don't know what your problem is... – harry Jan 03 '13 at 18:47
  • No it doesn't work, read["Price"] is already "29995.0" at that time. – Louisa Jan 03 '13 at 23:28
  • Adding this line somewhere in the code fixes the problem (I added it to the form load event): `System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");` – Louisa Jan 03 '13 at 23:53
0

Try

MySQLCommand cmd = new MySQLCommand("SELECT Price FROM Products", connection);
MySQLDataReader reader = cmd.ExecuteReaderEx();

if (reader.HasRows)
{
  while (reader.Read())
  {
    price = double.Parse(reader["Price"]).ToString());
  }
}

price variable should be in double data type

Jobert Enamno
  • 4,403
  • 8
  • 41
  • 63
  • Have tried this, it didn't work. But thanks for giving it a try. – Louisa Jan 03 '13 at 12:01
  • What's your CultureInfo? If your database records were saved using American format but your machine has Spanish or other Culture then you will not get the same per your database format. – Jobert Enamno Jan 03 '13 at 12:06