PostgreSQL类型转换函数 to_char( ***, text), to_number(***,text)
PostgreSQL类型转换函数
将数值转成字符串类型
调用to_char(int, text)函数,int为要转换值,text为数值格式化模式
| 模式 | 描述 |
|---|---|
| 9 | 带有指定数值位数的值 |
| 0 | 带前导零的值 |
| .(句点) | 小数点 |
| ,(逗号) | 分组(千)分隔符 |
| PR | 尖括号内负值 |
| S | 带符号的数值 |
| L | 货币符号 |
| D | 小数点 |
| G | 分组分隔符 |
| MI | 在指明的位置的负号(如果数字 < 0) |
| PL | 在指明的位置的正号(如果数字 > 0) |
| SG | 在指明的位置的正/负号 |
- eg
SELECT to_char(12345, '9999999999999999999')
//结果‘ 12345’,结果字符串前面有空格,位数跟格式化模式中9的位数有关;
SELECT to_char(12345, '99999')
//结果‘12345’
SELECT to_char(12345, '9999')
//结果‘####’,当模式串小于数字个数时,字符串会显示为#,位数跟格式化模式中9的位数有关;
将字符串转成数值
方法调用: to_number(text,text)函数,参数1是要转的数字字符串,参数2为模式参数
其他转换Function
| Function | ReturnType | Description | Example |
|---|---|---|---|
| to_char(timestamp, text) | text | converttimestamptostring | to_char(current_timestamp,‘HH12:MI:SS’) |
| to_char(interval, text) | text | convertintervaltostring | to_char(interval’15h022m0212s’,‘HH24:MI:SS’) |
| to_char(int, text) | text | convertintegertostring | to_char(404,‘999’) |
| to_char(double precision, text) | text | convertreal/double precisiontostring | to_char(404.8::real,‘999D9’) |
| to_char(numeric, text) | text | convertnumerictostring | to_char(-404.8,‘999D99S’) |
| to_date(text, text) | date | convertstringtodate | to_date(‘0502Dec022000’,‘DD02Mon02YYYY’) |
| to_number(text, text) | numeric | convertstringtonumeric | to_number(‘12,454.8-’,‘99G999D9S’) |
| to_timestamp(text, text) | timestampwithtimezone | convertstringtotimestamp | to_timestamp(‘0502Dec022000’,‘DD02Mon02YYYY’) |
| to_timestamp(double precision) | timestampwithtimezone | convertUnixepochtotimestamp | to_timestamp(1284352323) |
本文详细介绍了PostgreSQL中的类型转换函数to_char和to_number的使用方法,包括如何将数值转换为字符串,以及如何将字符串转换为数值。to_char函数通过指定格式模式来控制输出字符串的样式,例如添加前导零、货币符号等。而to_number函数则用于将符合特定模式的字符串解析为数值。此外,还提到了其他如to_date、to_timestamp等转换函数的使用示例。
1895





