简体   繁体   English

Oracle SQL-四舍五入

[英]Oracle SQL - Round - Half

Oracle ROUND function rounds "half up" by default : 默认情况下,Oracle ROUND函数将“向上舍入”:

select 3.674 my_number,
       round(3.674,2) round_on_number
from   dual
union
select 3.675 my_number,
       round(3.675,2) round_on_number
from   dual
union
select 3.676 my_number,
       round(3.676,2) round_on_number
from   dual
;

 MY_NUMBER ROUND_ON_NUMBER
---------- ---------------
     3,674            3,67
     3,675            3,68
     3,676            3,68

I need to round "half down", which essentially means that I should get the following result instead : 我需要四舍五入,这实际上意味着我应该得到以下结果:

 MY_NUMBER EXPECTED_ROUND_ON_NUMBER
---------- ------------------------
     3,674                     3,67
     3,675                     3,67
     3,676                     3,68

It should be fast as I need to do this on millions of items. 它应该很快,因为我需要对数百万个项目执行此操作。

I could probably detect if the number ends with a "5" and trunc that last digit in that case, round otherwise, but I have the feeling this will be inefficient (?) 我可能可以检测到数字是否以“ 5”结尾,并在这种情况下截断最后一位数字,否则四舍五入,但是我感觉这效率低下(?)

Thank you ! 谢谢 ! David 大卫

The documentation shows you the algorithm used : 该文档向您展示了所使用的算法

  1. If n is 0, then ROUND always returns 0 regardless of integer. 如果n为0,则ROUND始终返回0,而不考虑整数。
  2. If n is negative, then ROUND(n, integer) returns -ROUND(-n, integer). 如果n为负,则ROUND(n,integer)返回-ROUND(-n,integer)。
  3. If n is positive, then 如果n为正,则
    ROUND(n, integer) = FLOOR(n * POWER(10, integer) + 0.5) * POWER(10, -integer)

So you could modify the positive, non-zero version: 因此,您可以修改正的非零版本:

FLOOR(n * POWER(10, integer) + 0.4) * POWER(10, -integer)
                                 ^

eg for a fixed rounding, and ignoring zeros/negative for now: 例如,对于固定的舍入,现在暂时忽略零/负数:

with t (my_number) as (
  select 3.674 from dual
  union all select 3.675 from dual
  union all select 3.676 from dual
)
select my_number,
  floor(my_number * power(10, 2) + 0.4) * power(10, -2) as round_on_number
from  t;

 MY_NUMBER ROUND_ON_NUMBER
---------- ---------------
     3.674            3.67
     3.675            3.67
     3.676            3.68

You could include zero/negative via a case expression; 您可以通过case表达式包含零/负数; or write your own function to handle it more neatly. 或编写自己的函数来更整洁地处理它。

Knock .001 from the value, then round as normal: 从值中剔除.001,然后正常舍入:

select round(my_number-.001,2)
from MyTable

For rounding to 3dp, change to -0.0001 , etc 要舍入到3dp,请更改为-0.0001-0.0001

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

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