为什么 Sql Server 2000 上的 TSQL 对小数点的舍入不一致?
我正在尝试计算美元金额的折扣百分比。在 50% 的情况下,有时你会得到半分钱,我需要将其四舍五入到最接近的一分钱。
在 Sql 中,我的计算如下:
round(retail * 0.5, 2, 0)
如果我采用以下值,我会得到不同的结果:
- 4.39
- 2.49
Unrounded 我得到:
- 4.39 --> 2.195
- 2.49 --> 1.245
四舍五入后得到:
- 2.195 --> 2.19
- 1.245 --> 1.25
我听说这是“银行舍入”的一种形式,但似乎影响舍入方向的值是整数值。
我的问题是我期望最高值四舍五入到 2.20。如果这确实是银行家四舍五入,并且它受到此处整数值的影响,是否有人有一个例子来防止这种行为。如果不是银行家四舍五入,有人可以提供解释和可能的解决方案来获得正常的四舍五入行为吗?
提前致谢!
I'm trying to calculate percent off values for dollar amounts. At 50%, sometimes you get half a penny, and I need to round it to the nearest cent.
In Sql, my calculation is as follows:
round(retail * 0.5, 2, 0)
If I take the following values I get different results:
- 4.39
- 2.49
Unrounded I get:
- 4.39 --> 2.195
- 2.49 --> 1.245
When rounded I get:
- 2.195 --> 2.19
- 1.245 --> 1.25
I'm told this is a form of "banker's rounding", but it seems like the value that is affecting the rounding direction is the integer value.
My problem is that I expect the top value to round to 2.20. If this is indeed bankers rounding, and it is affected by the integer value here, does anyone have an example for preventing this behavior. If it is not bankers rounding, can someone please provide an explanation and potentially a solution to just get normal rounding behavior?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
retail
的数据类型是什么?我无法在 SQL 2000 上对此进行测试,但在 SQL 2008 R2 上,如果使用float
,我会看到类似的结果。要显示
float
创建的近似值,您可以转换为decimal(20,19)
,这样就可以清楚为什么它会这样舍入:What is the data type of
retail
? I can't test this on SQL 2000, but on SQL 2008 R2, I see similar results if I usefloat
.To show the approximation created by
float
, you can cast todecimal(20,19)
and it becomes clear why it's rounding this way:在这里查看一些舍入方法:SQL Server 舍入方法 银行家四舍五入解释
Take a look at some rounding methods here: SQL Server Rounding Methods bankers rounding is explained