I have a float column in SQL Server with value 21.261 , when I am fetching this column into c# double , using entity framework core 2.0 it is becoming 21.2610000000042, how to avoid this and get the exact value as 21.261
Asked
Active
Viewed 190 times
-3
-
1Here are some good explanations on why it happens: [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Zohar Peled Sep 08 '19 at 07:45
-
Need to see your fetching code. Also your Model too – Selim Yildiz Sep 08 '19 at 08:39
-
Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Progman Sep 08 '19 at 10:56
1 Answers
0
As you may have noticed , your number is probably not exactly 21.261, but only some pretty accurate approximation.
Depending on what your data really represents you could use a different database storage type like ‘DECIMAL’ ... that would typically help when storing monetary values, that have ‘cents’.
However, depending on the programming language being capable of working with rational numbers or fractions, the moment you would read in the data back into a float, you again have to deal with these issues and likewise have to deal with it during printing etc.

vanHoesel
- 956
- 9
- 22
-
The value in the database is exactly 21.261 but it is becoming 21.26100000042 in c# while fetching – Tamajit Sep 08 '19 at 08:34
-
No. 21.261 can *not* be represented exactly by a float. Neither in SQL Server not in C#. See the link given by Zohar Peled in his comment – Klaus Gütter Sep 08 '19 at 08:45
-
@Tamajit, you wrote, that it is a FLOAT column. Those columns hold numbers as a binary or 'base-2' number. There is no way to represent (decimal or base-10) 21.261 number in a 'base-2' system. Just as it is impossible to represent ⅓ in a 'base-10' system, 0.333… looks like a acceptable solution, but it is not exactly the same, neither would it be with 20 more following digits. And thus your SQL server does NOT hold that exact number at all .. or it's not using a FLOAT as you suggested. – vanHoesel Sep 08 '19 at 09:07