oracle格式掩码返回小数位

时间:2018-07-06 08:06:41

标签: sql oracle

我的小数位数有问题。 我想以10.50、1.53、1.004、1200.00的格式获得赔率

select to_char(1.004,'9999.00') from dual;

从此选择中,我得到1.00,但我需要1.004。

SELECT rtrim(to_char(10.51, '9999.999'), '0') FROM DUAL;

由此我可以确定(10.51)的赔率,其中最后一个数字不为0.但是当赔率是10.50时我得到10.5,我不希望我至少需要在小数点后两位小数。

是否有可能在小数点后2位取整,但是当我得到3的数字时要显示小数点后3位。

2 个答案:

答案 0 :(得分:1)

仅当最后一个字符为零时,才可以使用正则表达式删除该字符:

regexp_replace(to_char(<value>, '9999.999'), '0$', null)

演示:

with your_table (odds) as (
  select 10.50 from dual
  union all select 1.53 from dual
  union all select 1.004 from dual
  union all select 1200.00 from dual
)
select odds, regexp_replace(to_char(odds, '9999.999'), '0$', null) as formatted
from your_table;

      ODDS FORMATTED
---------- ---------
      10.5    10.50  
      1.53     1.53  
     1.004     1.004 
      1200  1200.00  

您可以使用普通的字符串函数,例如instrsubstr,但这里有点混乱。

或者您可以使用案例表达式来确定要使用的格式模型:

to_char(<value>,
  case when <value> = trunc(<value>, 2) then '9999.99'
       else '9999.999' end)

case when <value> = trunc(<value>, 2) then to_char(<value>, '9999.99')
     else to_char(<value>, '9999.999') end

或类似的变体(例如,现在决定要包含多个9)。

演示:

with your_table (odds) as (
  select 10.50 from dual
  union all select 1.53 from dual
  union all select 1.004 from dual
  union all select 1200.00 from dual
)
select odds,
  case when odds = trunc(odds, 2) then to_char(odds, '9999.99')
       else to_char(odds, '9999.999')
  end as formatted
from your_table;

      ODDS FORMATTED
---------- ---------
      10.5    10.50 
      1.53     1.53 
     1.004     1.004
      1200  1200.00 

答案 1 :(得分:0)

尝试一下

Select to_char(12.5, rtrim(lpad(' ',length(trunc(12.5))+1, '9'))||'.'||rtrim(lpad(' ', case when length(12.5 - trunc(12.5)) <= 2 Then 3 else length(12.5 - trunc(12.5)) end, '0'))) from dual

注意:将12.5更改为任意数字。它会根据您的要求返回