Avrohom Yisroel
Avrohom Yisroel

Reputation: 9440

Why does my C# decimal value get rounded to an integer

I have a class that includes a Decimal public property (generated by Entity Framework, code shown lower down), and am having problems with it being rounded to an integer.

I am reading a text file, and parsing the numbers as follows (most code elided for clarity)...

decimal val = decimal.Parse(str);
Transaction t = new Transaction {
  Value = val
};

If I examine val, I can see that it contains the full value, eg 9.99, and if I examine the Value property, it's correct. However, when the object is saved to the database, the value is rounded to the nearest integer, losing the fractional part.

The database has the field defined as decimal(18,0), and EF picked up on this and used the Decimal type for the property.

Here is the code that the EF generated for the property...

    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
    [DataMemberAttribute()]
    public global::System.Decimal Value
    {
        get
        {
            return _Value;
        }
        set
        {
            OnValueChanging(value);
            ReportPropertyChanging("Value");
            _Value = StructuralObject.SetValidValue(value);
            ReportPropertyChanged("Value");
            OnValueChanged();
        }
    }
    private global::System.Decimal _Value;
    partial void OnValueChanging(global::System.Decimal value);
    partial void OnValueChanged();

Anyone any ideas what's going wrong?

Upvotes: 4

Views: 2682

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499770

The database has the field defined as decimal(18,0)

That's the problem then. The 0 here is the scale. To quote the documentation:

scale: The number of decimal digits that will be stored to the right of the decimal point.

In other words, your database column can only hold integers. I suspect you want something like decimal(28,10) (depending on what your values are).

Upvotes: 15

Related Questions