Precision scale using Entity Framework and SQL Server

1

I have noticed some strange time saving values double in the SQL Server database with the Entity Framework.

I noticed that when reporting a value ex: 12.23 after saving the information is breaking the decimals in more houses ex: 12.22501.

This does not occur often and not every time a value is written, and it also has no impact on the calculations (since I do not use round ).

My questions are:

  • Why does this occur?
  • Has anyone ever gone through this? How did you decide?
  • Is this setting or depends on the database type?

The structure I use is the information below:

public class MyClass
{
    public double MyClass { get; set; };
}

public class MyContext : DbContext
{
    public DbSet<MyClass> MyClass;
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyClass>().Property(x => x.ValorTeste).HasPrecision(16, 5);
    }
}
    
asked by anonymous 08.08.2016 / 22:22

1 answer

4
  

Why does this occur?

Because the value written to double is used for scientific calculations where performance is required and the processor has specialized instructions that do the calculations very quickly. Because it's all done in binary rather than decimal form, as we're accustomed to, it achieves great speed and precision, but it does not get accuracy in many situations. For science, computer graphics and stuff like that, that's usually not a problem. For financial use is a huge problem.

  

Has anyone ever gone through this? how did you solve it?   Is it setting or depends on the database type?

Every programmer who used double where he could not have already gone through it and had some damage. The workaround is to use the correct type for the need, or decimal (existing in .Net and SQL Server) or money (only exists in SQL Server needing a mapping done by Entity Framework).

With the right type nothing needs to be configured.

Note that what will be displayed still depends on specific formatting, but presentation is different from the value itself. Calculations may still need rounding and adjustments, but all will work correctly with cents or other decimal parts of a number.

The performance may not be magnificent, but it's still great for this kind of application. Not even compared, for example with a text that is absurdly slower in most situations.

There is no workaround while using double . Any other attempt to make double behave accurately will fail. The worst is that in some cases it can work and the programmer thinks it worked. Many programmers firmly believe that it is possible to use double with accuracy, although it is well proven that not.

More information on another question here on the site .

    
08.08.2016 / 22:36