Oracle - 格式化数字,包含千位的逗号和小数点的逗号

时间:2015-01-26 15:16:00

标签: sql oracle number-formatting

我有这样的数字3225,69,我想将显示转换为:

3.225,69

简单地说,我需要完全停止将千位和逗号分开来分隔小数:

3,69 -> 3,69 
1000 -> 1.000 
1500,20 -> 1.500,20
1 -> 1 (not 1,000)

我应该在to_char中使用哪个掩码?

我的数据库列中逗号表示小数。

2 个答案:

答案 0 :(得分:9)

您可以使用FM format modifier删除尾随的十进制零:

select to_char(1, 'FM9G999G999D999', 'NLS_NUMERIC_CHARACTERS='',.''') from dual;

TO_CHAR(1,'FM9G999G999D999','NLS_NUMERIC_CHARACTERS='',.''')
------------------------------------------------------------
1,      

但是正如你所看到的那样留下十进制字符;你可以修剪它:

with t as (
 select 3.69 as n from dual
 union all select 1000 from dual
 union all select 150.20 from dual
 union all select 1 from dual
 union all select 0.16 from dual
)
select n,
  to_char(n, '9G999G999D000') original,
  to_char(n, 'FM9G999G999D999', 'NLS_NUMERIC_CHARACTERS='',.''') new,
  rtrim(to_char(n, 'FM9G999G999D999', 'NLS_NUMERIC_CHARACTERS='',.'''),
    ',') as trimmed
from t;

         N ORIGINAL       NEW            TRIMMED       
---------- -------------- -------------- --------------
      3.69          3.690 3,69           3,69           
      1000      1,000.000 1.000,         1.000          
     150.2        150.200 150,2          150,2          
         1          1.000 1,             1            
       .16           .160 ,16            ,16            

我使用the to_char() function的可选第三个NLS参数来独立于会话设置设置G和D字符。

如果您想保留小数点分隔符的零,只需将9之前的D变为0

with t as (
 select 3.69 as n from dual
 union all select 1000 from dual
 union all select 150.20 from dual
 union all select 1 from dual
 union all select 0.16 from dual
)
select n,
  to_char(n, '9G99G990D000') original,
  to_char(n, 'FM9G999G990D999', 'NLS_NUMERIC_CHARACTERS='',.''') new,
  rtrim(to_char(n, 'FM9G999G990D999', 'NLS_NUMERIC_CHARACTERS='',.'''),
    ',') as trimmed
from t;

         N ORIGINAL      NEW            TRIMMED       
---------- ------------- -------------- --------------
      3.69         3.690 3,69           3,69           
      1000     1,000.000 1.000,         1.000          
     150.2       150.200 150,2          150,2          
         1         1.000 1,             1              
       .16         0.160 0,16           0,16           

答案 1 :(得分:0)

你可以试试这个

select rtrim(to_char(to_char(1, 'FM9G999G999D999', 'NLS_NUMERIC_CHARACTERS='',.'''), 'FM9G999G999D999', 'NLS_NUMERIC_CHARACTERS='',.'''),',') from dual;

我希望能帮到你