項目需要使用百分率,保留2位小數,只用 round 和 trunc 函數都可以實現(round(_data,2) ),只是格式不是很工整,對格式要求不嚴謹的情況下使用 round 即可。
以下是比較方便的一種 :
select decode(n_jg,0,'0.00',trim(to_char(n_jg,'9999999.99'))) from table1
1、如果只是檢索,可使用:
select trunc(CUR_SUM,2) from data_record;
將小數轉化成百分比=> round(zcbj/zs*100)||'%' ==trunc((zcbj/zs),2)*100||'%'
2、如果更新數據,可使用:
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
不足之處是,如果數值是0的話,會顯示為.00而不是0.00。
另外注意,格式中小數點左邊9的個數要夠多,否則查詢的數字會顯示為n個符號“#”。
實例如下:
select decode(salary,0,'0.00',(to_char(round(salary,2),'fm99999999999999.00'))) from can_do;
方法二:使用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
方法三:可以使用Oracle自帶的參數設置
column amount format l9999999999.99
此方法的不足是,format中的小數點左面的9的個數要已知,否則會出現超過的數字顯示為########的情況。
另外需注意的是,使用column時,設置生效是session級還是system級。
也許某張表的數值列不總是要求所有的地方顯示時,都是小數點后兩位的格式,此時只能使用session級,但是有個數據庫連接會話超時的問題,如果不是使用到system級,不建議使用該方法。
方法四:使用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',(to_char(round(salary,2),'fm99999999999999.00'))) from can_do;