简体   繁体   English

为什么我的C#十进制值四舍五入为整数

[英]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. 我有一个包含Decimal公共属性的类(由Entity Framework生成,代码显示在较低的位置),并且它有四舍五入到整数的问题。

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. 如果我检查val,我可以看到它包含完整的值,例如9.99,如果我检查Value属性,它是正确的。 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. 数据库的字段定义为十进制(18,0),并且EF在此处拾取并使用Decimal类型作为属性。

Here is the code that the EF generated for the property... 这是EF为该属性生成的代码......

    [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) 数据库的字段定义为十进制(18,0)

That's the problem then. 那就是问题所在。 The 0 here is the scale . 这里的0scale To quote the documentation : 引用文档

scale : The number of decimal digits that will be stored to the right of the decimal point. scale :将存储在小数点右侧的小数位数。

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). 我怀疑你想要decimal(28,10) (取决于你的价值观)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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