Why does TSQL on Sql Server 2000 round decimals inconsistently?

你离开我真会死。 提交于 2019-12-10 08:46:59

问题


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!


回答1:


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 use float.

float:         4.39 --> 2.195, rounds to 2.19 
               2.49 --> 1.245, rounds to 1.25

money:         4.39 --> 2.195, rounds to 2.20
               2.49 --> 1.245, rounds to 1.25

decimal(5,2):  4.39 --> 2.195, rounds to 2.20
               2.49 --> 1.245, rounds to 1.25

To show the approximation created by float, you can cast to decimal(20,19) and it becomes clear why it's rounding this way:

4.39 * 0.5 --> 2.1949999999999999000
2.49 * 0.5 --> 1.2450000000000001000



回答2:


Take a look at some rounding methods here: SQL Server Rounding Methods bankers rounding is explained



来源:https://stackoverflow.com/questions/7852892/why-does-tsql-on-sql-server-2000-round-decimals-inconsistently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!