inserting c# double values to sql server float field. (no fractional part) - c#

I am trying to insert double values to my database via EF 5. I generated EF entity model from db. There is a price column in the table which is float, and naturally EF generated a double type for the mapper class.
I read some string values from a file and convert it to double and save it to db. When I debug I can see that values are converted correctly. For example string value "120,53" is converted to double like 120.53, just fine. But when I save my context it goes to db like "12053".
What can cause such a problem? Is there any setting in SQL Server has anything to do with this?

I believe the problem is in your Convert.ToDouble and the , being used instead of a decimal. Without supplying the culture for the number it's likely instead interpreting the , as a thousandths separator and ignoring it. Try passing in CultureInfo.CurrentCulture as the second argument (IFormatProvider) if the culture of your environment is one where the , is used as a decimal. Or, since it looks like you're replacing a decimal with the , - just don't replace it.

Related

How to get NumericPrecision and Scale of a decimal from DataTable

I need to get the exact type of a column in a DataTable in C#.
In a simliar article on SO i found part of a solution:
DataTable st = reader.GetSchemaTable();
foreach (DataRow row in st.Rows)
{
Console.Write(string.Format("ColumnName:{0} DataType:{1} Ordinal:{2} Precision:{3} Size:{4} Scale:{5}",
row["ColumnName"], row["DataTypeName"], row["ColumnOrdinal"],
row["NumericPrecision"], row["ColumnSize"], row["NumericScale"]));
}
This works for string and date so far.
But for decimal i always recieve nullfor precision and scale.
I need those values to create a new table in another database.
The DataType returned is Decimal.
In the MSDN documentation it says that NumericPrecision returns null if it is no numeric data type, but decimal is kind of numeric?
So how do i get the exact precision of decimal values from the DataSet? Or rather what am I doing wrong?
edit:
I am trying to create some new SQL database based on old .dbf files from a FoxPro application.
So i want to read the columns, and create them in SQL, therefore I need the exact type of the column.
I tried with the .dbf and a new sql database.
I created a table in both to know the exact type for sure, for both databases i get those null returns. There is only a problem with the decimal/numeric values, for string and DateTime i get the Size.
For the .dbf I use a OleDbConnection.
For the SQL I use a SqlConnection, I get null if I try it for each.
From my experience with MySQL, the decimal datatype is numeric, but it can hold any precision or scale. If the database you are trying to create doesn't have the decimal datatype, you may need to convert it to a different type of number and possibly guess what precision and scale you need.

SQL INSERT with ExecuteNonQuery() inserts extra decimal places

I have an asp.net application written in C#. I have an insert button that takes user-entered information on the page, adds the values to a list, and sends the list to a method that inserts the data to a MSSQL database table.
Everything is working as expected except for fields with data type set to 'float' on the backend.
If I enter a value such as '70.3' in the textbox for field 'Temperature', the value inserted actually becomes '70.3000030517578'. I also have a button that calls an update method. If I change the '70.3000030517578' back to '70.3' and send it to the update method, then 70.3 is correctly inserted in the database.
Here is my SqlCommand Parameter code:
cmd.Parameters.AddWithValue("#temp", listIn[0].Temperature == null ? (object)DBNull.Value : listIn[0].Temperature);
After the above line runs, I check the parameter in debugging mode and confirmed that the Value is 70.3. See screenshot:
I compared this to the update since that method works properly and the properties become:
The two differences are in the DbType and SqlDbType.
So I tried the below line which did not change anything (still adds extra decimal places):
cmd.Parameters.Add("#temp", SqlDbType.Float).Value = listIn[0].Temperature == null ? (object)DBNull.Value : listIn[0].Temperature;
If I change the data type on the backend to decimal(18,3) then the insert method correctly inserts '70.300'. Is my only option to use decimal data type instead of float? We would prefer to use float, if possible. Any ideas are welcomed. I have not been doing this long so I apologize if my question is not detailed enough.
Read about Using decimal, float, and real Data
Approximate numeric data types do not store the exact values specified
for many numbers; they store an extremely close approximation of the
value. For many applications, the tiny difference between the
specified value and the stored approximation is not noticeable. At
times, though, the difference becomes noticeable. Because of the
approximate nature of the float and real data types, do not use these
data types when exact numeric behavior is required, such as in
financial applications, in operations involving rounding, or in
equality checks. Instead, use the integer, decimal, money, or
smallmoney data types.
You're probably running into something related to floating point precision/error. 70.3 is not a value that can be precisely represented in the float/real type. The closest value that can be stored (following IEEE-754 standards) is 70.30000305175781
http://www.h-schmidt.net/FloatConverter/IEEE754.html
If you need accuracy in base 10, decimal is probably the way to go. Otherwise, you'll have to do the rounding yourself.

how to migrate doubles and dates from System.Data.OracleClient to ODP.NET?

This migration seem to be really challenging. What i'm trying to do now is to execute simple queries to a oracle db table:
OBJECTID NOT NULL NUMBER,
DOUBLEVALUE NOT NULL FLOAT(126),
MODTIME DATE
when I use System.Data.OracleClient I can INSERT parametrized queries where parameter values are:
123,
"123.123",
DateTime.Now.ToString().
and DbParameter.DbTypes are:
DbType.Int32,
DbType.Double,
DbType.Date
If I use Oracle.DataAccess.Client this is not working:
For DOUBLEVALUE I get exception because in my system Convert.ToDouble (which is called by OracleParameter.PreBind_Double) expects that I use comma ("123,123"). I do not want to change all the values in all programs and files. Also OleDb can handle this without problems.
For MODTIME I get "ORA-01830: date format picture ends before converting entire input string." This works if I change the value to DateTime.Now.ToShortDateString(). Possibly also if I change the parameter type. Also this OleDb can handle.
It seems ridiculous that Oracle.DataAccess.Client cannot handle these really basic situations which System.Data.OracleClient and System.Data.OleDb have no problems. Any recommendations?
Thanks & Best regards -Matti
Your problem with the comma comes from the default culture used by your processing thread. Try forcing en-US culture:
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");

SQL adding random Decimal points when getting a real from DB to a Double in C#

When I am Entering a double number from C# to the DB I use a real type in the DB. When I check the value it is exactly what I enter.
Now when I go to retreive the value from the DB and store it into a C# double, it adds random decimal values at then end. The number in the database is the correct value that I want, but the value in C# as a double is just random (sometimes higher sometimes lower then the actual value.)
ie
- Enter into the db 123.43 as a double to an sql real.
- View the value in the DB, it's exactly 123.43
- Get the value from the DB and store into a C# double, value in the double is now 123.4300000305176
I have tried changing the type to float, decimal, etc. in the DB but these types actually alter the value when I put it into the DB to the same format as the above.
Any help on whats going on or how to fix it?
You should probably be using Decimal type. See What represents a double in sql server? for further explanation.
Try using a Single if your DB type is real. Check here for data mappings http://msdn.microsoft.com/en-us/library/ms131092.aspx

SQLite saves float values in integer

I'm using System.Data.SQLite to save data to database. In table there are 2 columns defined as float. However when I save data to DB it saves only integer part.
12.2345 => 12
11.5324 => 11
(I don't know how exactly it rounds, it just rounds)
Yes I'm sure I'm using floats in my application, and I'm sure that CommandText contains float numbers NOT integer.
You need to be using floats in your application, but you also need to make sure the table entry in the SQLite database has been explicitly declared to be that REAL type.
There is no support for floats as build-in type. Use TEXT instead.

Categories

Resources