Abhishek Jain
Abhishek Jain

Reputation: 189

Entity framework Core is adding digits when converting float (db data type) to double in c#

I have a SQL table which has two columns Latitude and Longitude with values 29.47731 and -98.46272 respectively. Column datatype is float in SQL server.

When we retrieve the record using EF core like _context.Table.ToListAsync(), it retrieves record but when it is converted to c# equivalent double? datatype, it adds extra digits like -98.4627199999999.

How can i avoid this? It should return same value as there in database.

Upvotes: 2

Views: 2010

Answers (2)

THEoneANDonly
THEoneANDonly

Reputation: 421

I you find out that your data isn't stable and you are dealing with decimal values, it is propably a 'precise notation' issue.

Try taking a look at these:

SQL: https://learn.microsoft.com/en-us/sql/t-sql/data-types/decimal-and-numeric-transact-sql?view=sql-server-ver15

C# https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types

Those should guide you trough using the most precise notation for your situation :-)

Upvotes: 0

Paul Pearce
Paul Pearce

Reputation: 2530

SQL Float and C# Double are imprecise data types, they store very close approximations of the number, but often not the exact number. If you need to maintain the exact values, you should use SQL Numeric data type which will allow you to specify the number of significant digits; and while the C# Decimal data type is still imprecise, it will provide a higher precision approximation than Double does.

Upvotes: 2

Related Questions