代码之家  ›  专栏  ›  技术社区  ›  civesuas_sine

返回小数点的Oracle格式掩码

  •  0
  • civesuas_sine  · 技术社区  · 7 年前

    我的选择有小数位的问题。 我想得到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;
    

    从这里我得到了OK(10.51)的赔率,最后一个数字不是0。但当奇数是10.50时,我得到了10.5,我不希望在点后至少有两个小数位。

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

    2 回复  |  直到 7 年前
        1
  •  1
  •   Alex Poole    7 年前

    只有当最后一个字符为零时,才能使用正则表达式删除它:

    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  
    

    你可以使用普通的字符串函数,比如 instr substr 但这里有点乱。

    或者您可以使用case表达式来决定要使用的格式模型:

    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 
    
        2
  •  0
  •   Gaj    7 年前

    试试这个

    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改为任意数字。它将根据您的要求返回