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:
In the other word, I want to EF
save decimal places that end user specified in Value
.
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.