Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 655
Avrohom Yisroel Avatar asked Oct 19 '25 04:10

Avrohom Yisroel


1 Answers

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).

like image 121
Jon Skeet Avatar answered Oct 21 '25 16:10

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!