简体   繁体   中英

Why does TSQL on Sql Server 2000 round decimals inconsistently?

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!

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

看一下这里的一些舍入方法:解释SQL Server舍入方法银行家舍入

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