Eliminating decimals from whole numbers only

时间:2018-01-25 16:20:24

标签: plsql oracle-sqldeveloper

I have a column with a range of numbers.

row1: 3.4
row2: 4.00
row3: 5.23
row4: 2.0
row5: 0.00
row6: 000

I would like the final result to be

row1: 3.4
row2: 4
row3: 5.23
row4: 2
row5: 0
row6: 0

I basically want to remove decimals if it's a whole number or 0.

1 个答案:

答案 0 :(得分:0)

一个简单的方法,假设它们都代表有效数字,只是将它们从字符串转换为数字然后再转回:

with t (id, str) as (
            select 1, '3.4' from dual
  union all select 2, '4.00' from dual
  union all select 3, '5.23' from dual
  union all select 4, '2.0' from dual
  union all select 5, '0.00' from dual
  union all select 6, '000' from dual
)
select id, str, to_char(to_number(str)) as result
from t;

        ID STR  RESULT                                  
---------- ---- ----------------------------------------
         1 3.4  3.4                                     
         2 4.00 4                                       
         3 5.23 5.23                                    
         4 2.0  2                                       
         5 0.00 0                                       
         6 000  0                                       

这会将0.1的初始值显示为.1;如果你想在这种情况下保留前导零,你可以使用:

rtrim(to_char(to_number(str), 'FM999999990.99999'), '.')

为您的数据提供格式掩码,其中包含足够的前导9占位符:

with t (id, str) as (
            select 1, '3.4' from dual
  union all select 2, '4.00' from dual
  union all select 3, '5.23' from dual
  union all select 4, '2.0' from dual
  union all select 5, '0.00' from dual
  union all select 6, '000' from dual
  union all select 7, '01' from dual
  union all select 8, '00.10' from dual
)
select id, str, rtrim(to_char(to_number(str), 'FM999999990.99999'), '.') as result
from t;

        ID STR   RESULT          
---------- ----- ----------------
         1 3.4   3.4             
         2 4.00  4               
         3 5.23  5.23            
         4 2.0   2               
         5 0.00  0               
         6 000   0               
         7 01    1               
         8 00.10 0.1             

另一种选择是只转换为查询中的数字,让客户端或其他任何消费者决定如何格式化它。