How to store 3 decimals in a float column with Entity Framework Core? RRS feed

  • Question

  • Hello,

    After read some post, I have realized that I have made a mistake creating a float column instead of decimal for money purposes.

    Actually, the logic for this application is store a number with 3 decimals, but we are using a float column to store this value. Unfortunately, the table is storing values like "2.002000123445" instead of "2.002" even if the value has 3 decimals during the execution of the storing.

    At this point, its very hard to change the data type to Decimal to this column because it will mean a huge impact in the solution. So, I would like to know if it is possible to set a precision for a float column using Entity Framework Core or force to round the value during the storing process.

    The data type in table in SQL Server is: float

    The propery in Entity class is: 

    public double ConvertFactor { get; set; }

    I have read this posts:

    The question is: How to force to save 3 decimals using EF?I know it is possible to save 3 decimals using SQL Server.

    Thank you!


    Friday, March 27, 2020 8:04 AM


  • Hello again!

    After some more research, I have found a way to use ValueConverter.

    So, I have just added this

    b.Property(x => x.ConvertFactor).HasConversion(DbContext.FloatKindConverter);
    Where DbContext.FloatKindConverter is an instance of this class
     public class FloatKindConverter : ValueConverter<double, double>
            public FloatKindConverter()
                :base(v => Math.Round(v, 3), v => Math.Round(v, 3))

    Thank you ;)!

    Friday, March 27, 2020 10:20 AM