LINQ to SQL-十进制数据类型被截断而不是四舍五入 [英] LINQ to SQL - Decimal datatype truncated instead of rounded

查看:158
本文介绍了LINQ to SQL-十进制数据类型被截断而不是四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个十进制(6,1)的DB列 使用LINQ to SQL保存记录时,它会将值截断而不是舍入.

I have a DB column of decimal(6,1) When saving a record with LINQ to SQL, it truncates the value instead of rounding.

因此,例如,如果传递给生成的LINQ to SQL查询中此列的参数具有此值... -@ p1:输入小数(大小= 0;精度= 6;小数位= 1)[222.259] 数据将在数据库中显示为222.2,而不是222.3

So for example, if a parameter passed to this column in the generated LINQ to SQL query has this value... -- @p1: Input Decimal (Size = 0; Prec = 6; Scale = 1) [222.259] the data will show up in the DB as 222.2 instead of 222.3

然后,如果我将数据库中的同一列更改为十进制(7,2),并且不将LINQ重新生成为SQL类,则使用LINQ保存记录仍会截断... -@ p1:输入小数(大小= 0;精度= 6;小数位= 1)[222.259] 数据将在数据库中显示为222.20,而不是222.26(或222.30)

Then, if I change the same column in the DB to be decimal(7,2) and I don't regenerate the LINQ to SQL classes, saving a record using LINQ will still truncate... -- @p1: Input Decimal (Size = 0; Prec = 6; Scale = 1) [222.259] the data will show up in the DB as 222.20 instead of 222.26 (or 222.30)

有人知道这是否是LINQ的正确行为吗?还是SqlServer提供程序?它的行为与在mgmt studio中手动编写查询的方式不同,这就是为什么我对为什么要截断而不是舍入感到困惑.

Does anyone know if this is the correct behavior for LINQ? Or is the SqlServer provider? It doesn't behave the same way as writing a query by hand in mgmt studio which is why I'm confused on why it is truncating instead of rounding.

mgmt studio中的以下查询... UPDATE TheTable SET TheDecimalColumn = 222.259 当列为十进制(6,1)时,将val设置为222.3;当十进制(7,2)时,将val设置为222.26

The following query in mgmt studio... UPDATE TheTable SET TheDecimalColumn = 222.259 will set the val to 222.3 when the column is decimal(6,1) and 222.26 when it is decimal(7,2)

谢谢

推荐答案

这是sqlparameter,它必须执行此操作,因为舍入小数不是标准的:有不同种类的舍入算法,它们以不同的方式使用在某些领域,例如银行业使用的舍入标准与其他方法不同.

It's the sqlparameter, and it has to do this, as rounding a fraction is not standarized: there are different kind of rounding algorithms, which are used in different kind of areas, like banking uses different kind of rounding standards than others.

如果要舍入,请在将值设置为实体之前自行对值进行舍入定义.这是合乎逻辑的,因为您将一个数字定义为小数位数,因此.256不适合一个数字,这意味着您要么应该获得异常(linq to sql对此不支持内存中验证),否则它会被截断在较低的水平.

If you want rounding, define it yourself by rounding the value before you set the value in the entity. It's logical as you defined a single digit as scale, so .256 doesn't fit in a single digit, which means you either should get an exception (linq to sql doesn't support in-memory validation for this) or it gets truncated in the lower levels.

这篇关于LINQ to SQL-十进制数据类型被截断而不是四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆