Oracle中用pl/sql實現貨幣數字格式到漢字格式的轉化
create or replace function Func1(p_num in number default null)
return varchar2
is
Result varchar2(100);
num_round varchar2(100) :=to_char(abs(round(p_num,2)));
--小數點後保留兩位(四捨五入)
num_left varchar2(100);
num_right varchar2(2);
str1 char(20) :='零壹貳叄肆伍陸柒捌玖';
str2 char(30) :='分角元拾佰仟萬拾佰仟億拾佰千萬';
num_pre number(1):=1;
num_current number(1);--用於從str1中取字元
num_count number:=2;--用於從str2中取字元
begin
--如果是空就返回
if p_num is null
then return null;
end if;
select to_char(nvl(substr(num_round,1,
decode(instr(num_round,'.'),0,length(num_round),instr(num_round,'.')-1)),0))
--0表示沒有找到,說明沒有小數
into num_left from dual;
select substr(num_round,
decode(instr(num_round,'.'),0,
length(num_round)+1,instr(num_round,'.')+1),2)
into num_right from dual;
--從小數點後取兩位,如果沒有小數部分,取兩位返回值應為空
if length(num_left)>13 then return '您輸入的數字太大,無法轉換!';
--如果整數數字大於13位,返回**********
end if;
--處理整數
for i in reverse 1..length(num_left) loop
num_count:=num_count+1;
num_current:=to_number(substr(num_left,i,1));
if num_current>0 then --不為零
result:=substr(str1,num_current+1,1)||substr(str2,num_count,1)||result;
else
if mod(num_count-3,4)=0 then--第5位、9位
result:=substr(str2,num_count,1)||result;
num_pre:=0;
end if;
end if;
end loop;
--處理小數
--角
--num_count number:=1;
num_current:=to_number(nvl(substr(num_right,1,1),0));
result:=result||substr(str1,num_current+1,1)||substr(str2,2,1);
--分
num_current:=to_number(nvl(substr(num_right,2,1),0));
result:=result||substr(str1,num_current+1,1)||substr(str2,1,1);
--負數
if p_num<0 then
result:='負'||result;
end if;
return Result;
exception
when others then
dbms_output.put_line('轉換出現錯誤!');
raise_application_error(-20001,'轉換出現錯誤!');
end Func1;
/