1. 程式人生 > >Oracle 保留兩位小數解決方案

Oracle 保留兩位小數解決方案

方式一:使用to_char的fm格式

to_char(round(data.amount,2),'FM9999999999999999.00') as amount
不足之處是,如果數值是0的話,會顯示為.00而不是0.00。
另一需要注意的是,格式中小數點左邊9的個數要夠多,否則查詢的數字會顯示為n個符號“#”。
解決方式如下:
select decode(salary,0,'0.00',(to_char(round(salary,2),'fm99999999999999.00'))) from can_do;

但是這種方式還有一個問題:就是類似0.84這樣的資料會顯示為.84.

解決方式,將小數點前的第一位置設為零即可,如下:

select decode(salary,0,'0.00',(to_char(round(salary,2),'fm99999999999990.00'))) from can_do;

注:FM只能去掉用9表示的格式中產生的0

方法二:使用case when then else end進行各種情況的判斷處理
case
when instr(to_char(data.amount), '.') < 1 then
data.amount || '.00'
when instr(to_char(data.amount), '.') + 1 = length(data.amount) then
data.amount || '0'
else
to_char(round(data.amount, 2))
end as amount_format

方式三:使用to_char+trim的方式

select trim(to_char(1234,'99999999999999.99')) from dual;
或者
select ltrim(trim(to_char(1234.525,'00000000000000.00')),'0') from dual;
此處使用了14個9或者14個0的格式,建議使用14個9的方式,方便些。方法四的不足之處是:
如果數值是0的話,轉化之後為.00而不是0.00,補救措施是,decode一下。
另一需要注意的是,格式中小數點左邊9或者0的個數要夠多,否則查詢的數字會顯示為n個符號“#”。
如下:
select decode(salary,0,'0.00',trim(to_char(salary,'99999999999999.99'))) from can_do;
或者

select decode(salary,0,'0.00',ltrim(trim(to_char(salary,'00000000000000.00')),'0')) from can_do;
結論:建議使用方法三中的trim+to_char的方式或者方法一的補救之後的方式,而且最好使用小數點左邊n個9的方式,不要使用0的方式,否則,要多一步trim處理。
即:select decode(salary,0,'0.00',trim(to_char(salary,'99999999999999.99'))) from can_do;

select decode(salary,0,'0.00',trim(to_char(salary,'99999999999990.99'))) from can_do;

或者
select decode(salary,0,'0.00',(to_char(round(salary,2),'fm99999999999999.00'))) from can_do;

select decode(salary,0,'0.00',(to_char(round(salary,2),'fm99999999999990.00'))) from can_do;

例子:

select decode(52.1008,0,'0.00',(to_char(52.1008,'fm99999999999999.00')))as p_number from dual;

select decode(0.84,0,'0.00',trim(to_char(0.84,'99999999999990.99')))as p_number from dual;