Search code examples
c#entity-frameworksql-server-2008decimaldecimal-point

Force EF to save specified decimal places


I defined some decimal properties in my entities:

public class Entity1
{
   public int Id { get; set; }

   public decimal Value {get; set;}
}

and because I want to save maximum 4 decimal places for my decimals, in my configuration files I defined:

this.Property(t => t.Value).HasPrecision(18, 4); 

so the result is Value field with 4 decimal places in my Entity1 table.

How can I force EF to save only decimal places that used in Value's value?

for example:

  • if Value = 0.05 then it save 0.05 and when I read the Value from Db it shows me 0.05 and not 0.0500
  • if Value = 0.050 then it save 0.050
  • if Value = 0.05000 then it save 0.0500 (because maximum decimal places is 4)

In the other word, I want to EF save decimal places that end user specified in Value.


Solution

  • Since your concern is about display the numbers the way they were entered and not as much with preserving the exact precision for mathematical reasons, you have a couple of options.

    I am assuming that you actually need the value to be numeric within the database, for querying or calculation purposes. Otherwise, you could save it as a string.

    You could save a second value, representing the precision of the entered value, and use that to create a format string for your value:

    public decimal  Value { get; set; }
    public byte     ValuePrecision { get; set; }
    
    public string FormatValue()
    {
        string fmtString = string.Format("{{0:N{0}}}", this.ValuePrecision);
        return string.Format(fmtString, this.Value);
    }
    

    DISCLAIMER: code was done from memory and has not been tested.