如何始终在 PL/SQL 中显示数字的两位小数

How to always show two decimal places on a number in PL/SQL

各位,

我有一个现有的存储过程,我正在尝试更新它以始终显示两位小数,即使它是整数或单个小数。

此存储过程生成的消息必须将 v_credit_amt 显示为两位小数,但分配给 v_credit_amt 的值可以是整数、一位小数或两位小数价值 即 175 应显示为 175.00,250.5 应显示为 250.50,395.95 应显示为 395.95。

这里是相关股票pl/sql

v_credit_amt        number(22,2);
select NVL(sit_credit_limit,0)
  into v_credit_amt
  from sites
 where sit_pkey = p_site_id;

我认为在 select 期间通过 to_char 格式化可以解决这个问题,唉

select NVL(to_char(sit_credit_limit, 'fm99999.00'),0)
  into v_credit_amt
  from sites
 where sit_pkey = p_site_id;

--v_credit_amt := to_char(v_credit_amt, 'fm99999.00');
insert into SQL_TXT values (v_credit_amt);
commit;

正如您从上面注释掉的行中看到的,一旦定义了 v_credit_amt 变量,我也试过了

我也用 to_number 函数试过了

select NVL(to_number(sit_credit_limit, '99999.00'),0)
  into v_credit_amt
  from sites
 where sit_pkey = p_site_id;

但是,如果 sit_credit_limit 列中存储的值是不带小数的整数,或者像 250.5 v_credit_amt 这样的数字,在查询 SQL_TXT table 我正在插入以进行调试。

SQL> select * from SQL_TXT;

COL1
--------------------------------------------------------------------------------
175
250.5

此特定事件只是将多个消息部分连接成一个返回的单个长消息字符串,即

if p_message_id = '14' then
   v_message := 'Comtrol Check In Message Posted';
   v_string  := v_string || '008' || lpad(length(v_fname || ' ' || v_lname), 3, '0') || v_fname || ' ' || v_lname;
   v_string  := v_string || '059' || lpad(1, 3, '0') || '0';
   --v_string  := v_string || '089' || lpad(1, 3, v_credit_amt) || to_char(v_credit_amt);
   v_string  := v_string || '089' || lpad(length(to_char(v_credit_amt, 'fm9999999.00')), 3, '0') || to_char(v_credit_amt, 'fm9999999.00');
   v_string  := v_string || '106' || lpad(length(nvl(v_acct_number,'')), 3, '0') || v_acct_number;
   --v_string  := v_string || '106' || v_acct_number;
   v_string  := v_string || '164' || lpad(1, 3, '0') || '0';
   v_string  := v_string || '174' || lpad(length(v_rm_phone_num), 3, '0') || v_rm_phone_num;
   v_string  := v_string || '175' || lpad(length(v_rm_id), 3, '0') || v_rm_id;
   v_string  := v_string || '183' || lpad(1, 3, '0') || '0';
endif;

但是我无法让最终字符串在所有用例中都正确地包含两位小数。

例如,如果数据库中的值为 125,我会得到这个作为最终字符串

144450034629999008009Bob Smith05900100{89006125}1060073307542164001017400340917500 34091830010

然而它应该是

144450034629999008009Bob Smith05900100{89007125.00}1060073307542164001017400340917500 34091830010

抱歉上面的格式,我看不出如何在没有代码块的情况下加粗部分,所以我突出显示了相关部分{}

如果我需要始终将数字显示为两位小数,即使给出了一个整数或一位小数,我还缺少什么?

实际上,您必须插入带格式的数据。 (假设目标列是 VARCHAR)无论您获取什么格式并将其放入 NUMBER 变量,都将是 NUMBER

数字毕竟没有保存格式。仅供展示,格式进入画面。

insert into SQL_TXT values (TO_CHAR(v_credit_amt,'FM99999.00'));
commit;

如果 INSERT-ed 列再次 NUMBER

你还想一起

SELECT TO_CHAR(COL1,'FM99999.00') FROM SQL_TEXT;