程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> Oracle數據庫 >> Oracle數據庫基礎 >> Oracle小數點的實際保留問題的4方案

Oracle小數點的實際保留問題的4方案

編輯:Oracle數據庫基礎

以下的文章主要是講述Oracle小數點的實際保留問題,如果你有相關的業務清單有提取要求的話,我們需要使用到百分率,通常的情況下,需要對其保留兩位小數,其實我們只用round就可以實現(round(_data,2) ),但是格式不是很工整。

對格式要求不嚴謹的情況下使用round即可,以下是網絡搜索到的處理方法:

方法一:使用to_char的fm格式,即:

  1. to_char(round(data.amount,2),'FM9999999999999999.00') as amount 

不足之處是,如果數值是0的話,會顯示為.00而不是0.00。

另一需要注意的是,格式中Oracle小數點左邊9的個數要夠多,否則查詢的數字會顯示為n個符號“#”。

解決方式如下:

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

方法二:使用case when then else end進行各種情況的判斷處理:

  1. case  
  2. when instr(to_char(data.amount), '.') < 1 then  
  3. data.amount || '.00'  
  4. when instr(to_char(data.amount), '.') + 1 = length(data.amount) then  
  5. data.amount || '0'  
  6. else  
  7. to_char(round(data.amount, 2))  
  8. end as amount_format  

方法三:可以使用Oracle自帶的參數設置,即

  1. column amount format l9999999999.99 

此方法的不足是,format中的Oracle小數點左面的9的個數要已知,否則會出現超過的數字顯示為########的情況。

另外一個問題是,使用column時,設置生效是session級還是system級,需要注意。

也許某張表的數值列不總是要求所有的地方顯示時,都是Oracle小數點後兩位的格式,

此時只能使用session級,但是有個數據庫連接會話超時的問題,如果不是使用到system級,不建議使用該方法。

方法四:使用to_char+trim的方式,如下:

  1. select trim(to_char(1234,'99999999999999.99')) from dual; 

或者

  1. select ltrim(trim(to_char(1234.525,'00000000000000.00')),'0') from dual; 

此處使用了14個9或者14個0的格式,建議使用14個9的方式,方便些。方法四的不足之處是

如果數值是0的話,轉化之後為.00而不是0.00,補救措施是,decode一下。

另一需要注意的是,格式中Oracle小數點左邊9或者0的個數要夠多,負責查詢的數字會顯示為n個符號“#”。

如下:

  1. select decode
    (salary,0,'0.00',trim(to_char(salary,'99999999999999.99'))) from can_do; 

或者

  1. select decode
    (salary,0,'0.00',ltrim(trim(to_char(salary,'00000000000000.00')),'0')) from can_do; 

結論:建議使用方法四中的trim+to_char的方式或者方法一的補救之後的方式,而且最好使用Oracle小數點左邊n個9的方式,不要使用0的方式,否則,要多一步trim處理。

即:

  1. select decode(salary,0,'0.00',
    trim(to_char(salary,'99999999999999.99'))) from can_do; 

或者

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

以上的相關內容就是對Oracle小數點的保留問題的介紹,望你能有所收獲。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved