Banker’s rounding-plsql function

本文在Oracle数据库中用pl/sql实现银行家算法的四舍六入五取偶。即:若需要舍入到的位的后面”小于5″或”大于5″的话,按通常意义的四舍五入处理.若”若需要舍入到的位的后面”等于5″,则要看舍入后末位为偶数还是奇数,偶数时直接舍弃,基数时进位。

create or replace function fn_bankers_round(val number, rnd number := 0)
  return number is
  v_rnd number;
  v_tmp number;
begin
  v_rnd := trunc(rnd);
  v_tmp := (trunc(val,v_rnd + 1) - trunc(val, v_rnd)) *
                 power(10, v_rnd + 1);
  if Abs(v_tmp) < 5 or
     (Abs(v_tmp) = 5 and
      mod(trunc(val * power(10, v_rnd)), 2) = 0) then
    return trunc(val, v_rnd);
  else
    return round(val, v_rnd);
  end if;
end;
/

输出结果

SQL> select fn_bankers_round(0.378453113,4) from dual;

FN_BANKERS_ROUND(0.378453113,4)
-------------------------------
                          .3784

SQL> select fn_bankers_round(0.378553113,4) from dual;

FN_BANKERS_ROUND(0.378553113,4)
-------------------------------
                          .3786

SQL> select fn_bankers_round(0.378443113,4) from dual;

FN_BANKERS_ROUND(0.378443113,4)
-------------------------------
                          .3784

SQL> select fn_bankers_round(0.378463113,4) from dual;

FN_BANKERS_ROUND(0.378463113,4)
-------------------------------
                          .3785

SQL> select fn_bankers_round(0.378433113,4) from dual;

FN_BANKERS_ROUND(0.378433113,4)
-------------------------------
                          .3784
此条目发表在algorithm, PLSQL分类目录。将固定链接加入收藏夹。

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s