to_char() 數據格式化


業務場景:

設備運行狀態類型0、1、2、3、4、5,當設備狀態處於1、2、3、4、的時候就返回該狀態下設備的值。

其他狀態給前端返回空,既然返回空,那就默認空串。

select (case when (a.type=1 or a.type=2 or a.type=3 or a.type=4) then to_char(a.realValue ,'fm9900.0099')  else '') as realvalue end from a where 1=1;

 

知識點一:

   to_char() 是oracle 的字符轉換函數。to_char(value,'format') value是待轉化的值,'format' 是轉化后的 pattern。

  這里樣式 fm9900.0099的包括如下含義:

  •  輸出的字符串總共占了9位,小數點前4位,小數點后4位。
  • 9代表含義,如果這個位置是數字就顯示數字,否則就用空格替代占位,總之要占住這個位置。
  • 0代表含義,如果這個位置是數字就顯示數字,否則就用0替代占位,總之要占住這個位置。

樣例如下(注意兩豎線之間是9個字符位置):

select to_char(37 ,'fm9900.0099')  from dual。

結果:------|    37.00    |-------

select to_char(37 ,'fm0000.0099')  from dual。

結果:------|0037.00  |-------

select to_char(37 ,'fm9900.9999')  from dual。

結果:------|    37.      |-------

所以如果要讓數字顯示出來看着不錯誤應該用這種格式

select to_char(37 ,'fm9990.00')  from dual。

小數點前必須有一個0,小數點后保留幾位小數就用幾個0。

結果:------|    37. 00   |-------

所以,第一次我的寫法其實是不恰當的,應該改為:

select (case when (a.type=1 or a.type=2 or a.type=3 or a.type=4) then to_char(a.realValue ,'fm9990.0000')  else '') as realvalue end from a where 1=1;

 

關注點:Number Format Elements

A number format model is composed of one or more number format elements. The tables that follow list the elements of a number format model and provide some examples.

Negative return values automatically contain a leading negative sign and positive values automatically contain a leading space unless the format model contains the MI, S, or PR format element.

注意紅色部分,意思是Number類型轉換為字符時,負數會返回前面包含負號的字符串,正數則會返回前面包含空格的字符串,除非格式模式包含MI、S、或PR元素。查看TO_CHAR(4, '0000')返回的字符串長度,你會發現其長度為5.

所以 ------|    37. 00   |------- 其實豎線之間輸出的字符串長度是10,因為前面還有一個默認的正值(空格)的占位。

知識點二:

to_char() 是oracle 的字符轉換函數。轉換的數據類型當然不止一種。

 日期轉換。

select to_char(sysdate,'yyyy-MM-dd HH24:mi:ss') from dual;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM