问题
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?
回答1:
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);
回答2:
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
来源:https://stackoverflow.com/questions/14138013/c-problems-with-getting-double-values-from-mysql-database