逗号后的 Oracle 四舍五入数字

Oracle rounding digits after comma

我想在 Oracle 中对数字进行四舍五入,以便仅在小数点后第三位的值后的逗号后保留 2 位数字。 我想要的示例:

1,374 --> 1,37
1,375 --> 1,37 (the 5 need to be rounding down)
1,3756 --> 1,37 (We only look the third decimal, even if the 4th is a 6)
1,376 --> 1,38

你会怎么做? 我检查了 ROUND() 函数,但行为不是我需要的。

感谢您的帮助

roundfloortrunc 结合使用,如下所示:

with t as (
  select column_value val 
    from table (sys.odcinumberlist(1.374, 1.375, 1.3756, 1.376)))
select val, 
       round(trunc(val, 3)-.0001, 2) v1, 
       round((floor(val*1000)-1)/1000, 2) v2
  from t

输出:

       VAL         V1         V2
---------- ---------- ----------
     1,374       1,37       1,37
     1,375       1,37       1,37
    1,3756       1,37       1,37
     1,376       1,38       1,38

您可以稍微调整四舍五入的值,例如:

round(trunc(<your number>, 3) - 0.001, 2)

trunc(<your number>, 3) 表示第三个小数点后的所有内容都将被忽略,因此 1,3756 将被视为与 1,375 相同。 - 0.001 然后稍微调整截断的值,以便正常的 round() 行为会使上下之间的临界点看起来在 .x6 而不是 .x5。

快速演示:

alter session set nls_numeric_characters =',.';

with t (n) as (
  select 1.37 from dual
  union all select 1.374 from dual
  union all select 1.374999 from dual
  union all select 1.375 from dual
  union all select 1.375001 from dual
  union all select 1.3756 from dual
  union all select 1.375999 from dual
  union all select 1.376 from dual
  union all select 1.37999 from dual
)
select n, round(n, 2) as simple, trunc(n, 3) as tmp1, trunc(n, 3) - 0.001 as tmp2,
  round(trunc(n, 3) - 0.001, 2) as adjusted
from t;

         N     SIMPLE       TMP1       TMP2   ADJUSTED
---------- ---------- ---------- ---------- ----------
      1,37       1,37       1,37      1,369       1,37
     1,374       1,37      1,374      1,373       1,37
  1,374999       1,37      1,374      1,373       1,37
     1,375       1,38      1,375      1,374       1,37
  1,375001       1,38      1,375      1,374       1,37
    1,3756       1,38      1,375      1,374       1,37
  1,375999       1,38      1,375      1,374       1,37
     1,376       1,38      1,376      1,375       1,38
   1,37999       1,38      1,379      1,378       1,38