简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM