0

I am using Microsoft SQL Server Management Studio and C# to insert some rows into this database. The first column of this table is a code (type varchar(20)) and the second one is a float. The problem arises because if I want to enter 3,71, the database stores 3,7100000381469727.

Code:

float superficieL = float.Parse(row.Cells[indexSuperficie].Value.ToString(), new CultureInfo("es-ES"));

The value inserted in the database as a float is this variable, and I get his value from a datagridview that only contains 3,71.

More examples:

  • (DB)001122 - 0,9100000262260437
  • (DB)335T1613 - 0,5
  • (DB)335T1642 - 3,869999885559082
  • (DB)335T1644 - 3,7100000381469727

Why is this happening?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
LuckWallace
  • 113
  • 10
  • what is data type in SQL table ? Are you able to retrieve it properly ? And I believe it is 3,71 after parsing and not 3,51 as you mentioned in question ? – Manoj Choudhari Jan 22 '20 at 16:14
  • @ManojChoudhari sorry Manoj, I've edited the post. – LuckWallace Jan 22 '20 at 16:17
  • 3
    https://floating-point-gui.de/ – CodeCaster Jan 22 '20 at 16:17
  • 1
    This is inherit to floating point. More information: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html. If you want to store numbers more accurately you can switch to using decimal datatype in MSSQL. – Valderann Jan 22 '20 at 16:20

1 Answers1

3

Please refer this article for understanding how float, double and decimal data type works in .NET

Also, please refer this article which suggests what are options available to store decimals in a SQL Server database.

You can either use real, float or decimal type for your case.

In your case, I would suggest to use the Decimal datatype in a SQL Server table, as it provides better precision and I believe that's what you asked for.

Hope this helps.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37