首页 > 解决方案 > 在PLSQL中将数字转换为varchar2,而PLSQL中没有千位分隔符

问题描述

有没有一种安全快速的方法将数字转换为 varchar2 而没有千位分隔符(无论排序规则或其他设置如何)。

例子:

/* Normal Collation */
1234.5 => '1234.5' (and not '1,234.5')
1.5 => '1.5'
/* Reverse Collation */
1234.5 => '1234,5' (and not '1.234,5')
1.5 => '1,5'

到目前为止,我所拥有的是:

declare
  thousand_separator# varchar2(1);
begin
  thousand_separator# := nullif(substr(to_char(1000), 2, 1), 0);

  dbms_output.put_line(case when thousand_separator# is null then to_char(123456.123) else replace(to_char(123456.123), thousand_separator#) end);
end;

我正在寻找类型to_char(<number>, 'CORRECT_FORMAT')或类似的东西(不会添加任何前导或尾随零)

标签: sqloracleplsqltype-conversion

解决方案


您可以使用TM文本最小”格式模型:

文本最小数字格式模型返回(以十进制输出)可能的最小字符数。

尽管这是默认情况下得到的,但无论如何您都to_char()没有使用模型。

带有小数点分隔符的演示:

alter session set nls_numeric_characters = '.,';

with t (num) as (
  select 1234.5 from dual
  union all
  select 1.5 from dual
  union all
  select 0.5 from dual
  union all
  select 0 from dual
  union all
  select 5 from dual
)
select to_char(num, 'TM') as str
from t;

STR                                                             
----------------------------------------------------------------
1234.5
1.5
.5
0
5

begin
  dbms_output.put_line(to_char(123456.123));
end;
/

123456.123
alter session set nls_numeric_characters = ',.';

with t (num) as (
  select 1234.5 from dual
  union all
  select 1.5 from dual
  union all
  select 0.5 from dual
  union all
  select 0 from dual
  union all
  select 5 from dual
)
select to_char(num, 'TM') as str
from t;

STR                                                             
----------------------------------------------------------------
1234,5
1,5
,5
0
5

begin
  dbms_output.put_line(to_char(123456.123));
end;
/

123456,123

推荐阅读