公司需要處理一些報(bào)表,需要使用百分率,保留2位小數(shù),只用round和trunc函數(shù)都可以實(shí)現(xiàn)(round(_data,2) ),只是格式不是很工整,對(duì)格式要求不嚴(yán)謹(jǐn)?shù)那闆r下使用round即可.
個(gè)人認(rèn)為比較方便的一種
select decode(n_jg,0,'0.00',trim(to_char(n_jg,'9999999.99'))) from tbl
如果只是檢索,可是使用:
1、select trunc(CUR_SUM,2) from data_record;
將小數(shù)轉(zhuǎn)化成百分比=> round(zcbj/zs*100)||'%' ==trunc((zcbj/zs),2)*100||'%'
2、如果想更新數(shù)據(jù),可以使用:
update data_record set CUR_SUM=trunc(CUR_SUM,2) where REC_NO=123
方法一:使用to_char的fm格式
to_char(round(data.amount,2),'FM9999999999999999.00') as amount
不足之處是,如果數(shù)值是0的話(huà),會(huì)顯示為.00而不是0.00。
另一需要注意的是,格式中小數(shù)點(diǎn)左邊9的個(gè)數(shù)要夠多,否則查詢(xún)的數(shù)字會(huì)顯示為n個(gè)符號(hào)“#”。
解決方式如下:
select decode(salary,0,'0.00',(to_char(round(salary,2),'fm99999999999999.00'))) from can_do;
方法二:使用case when then else end進(jìn)行各種情況的判斷處理
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
方法三:可以使用Oracle自帶的參數(shù)設(shè)置
column amount format l9999999999.99
此方法的不足是,format中的小數(shù)點(diǎn)左面的9的個(gè)數(shù)要已知,否則會(huì)出現(xiàn)超過(guò)的數(shù)字顯示為########的情況。
另外一個(gè)問(wèn)題是,使用column時(shí),設(shè)置生效是session級(jí)還是system級(jí),需要注意。
也許某張表的數(shù)值列不總是要求所有的地方顯示時(shí),都是小數(shù)點(diǎn)后兩位的格式,此時(shí)只能使用session級(jí),但是有個(gè)數(shù)據(jù)庫(kù)連接會(huì)話(huà)超時(shí)的問(wèn)題,如果不是使用到system級(jí),不建議使用該方法。
方法四:使用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個(gè)9或者14個(gè)0的格式,建議使用14個(gè)9的方式,方便些。方法四的不足之處是:
如果數(shù)值是0的話(huà),轉(zhuǎn)化之后為.00而不是0.00,補(bǔ)救措施是,decode一下。
另一需要注意的是,格式中小數(shù)點(diǎn)左邊9或者0的個(gè)數(shù)要夠多,負(fù)責(zé)查詢(xún)的數(shù)字會(huì)顯示為n個(gè)符號(hào)“#”。
如下:
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;
結(jié)論:建議使用方法四中的trim+to_char的方式或者方法一的補(bǔ)救之后的方式,而且最好使用小數(shù)點(diǎn)左邊n個(gè)9的方式,不要使用0的方式,否則,要多一步trim處理。
即:select decode(salary,0,'0.00',trim(to_char(salary,'99999999999999.99'))) from can_do;
或者
select decode(salary,0,'0.00',(to_char(round(salary,2),'fm99999999999999.00'))) from can_do;
新聞熱點(diǎn)
疑難解答
圖片精選