Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

to_char(number) function in postgres

i want to display/convert a number to character (of it's same length) using to_char() function .

In oracle i can write like

SELECT to_char(1234) FROM DUAL 

But in postgres SELECT to_char(1234) is not working.

like image 625
jobi88 Avatar asked Jan 04 '13 10:01

jobi88


People also ask

What is TO_CHAR in PostgreSQL?

The TO_CHAR function in PostgreSQL is used to convert various data types like date or time, integer, floating-point to formatted strings, and also, they can be used to convert formatted strings to specific data types. They are a part of Data type formatting functions.

How do I convert text to numeric in PostgreSQL?

Discussion: Use the :: operator to convert strings containing numeric values to the DECIMAL data type. In our example, we converted the string ' 5800.79 ' to 5800.79 (a DECIMAL value). This operator is used to convert between different data types.

How do I show AM PM in PostgreSQL?

select to_date(to_char(sysdate,'yyyy-mm-dd hh12:mi:ss AM'), 'yyyy-MM-dd HH12:MI:SS AM') from dual; This works fine in oracle but not in Postgres.

How do I convert text to date in PostgreSQL?

The TO_DATE function in PostgreSQL is used to converting strings into dates. Its syntax is TO_DATE(text, text) and the return type is date. The TO_TIMESTAMP function converts string data into timestamps with timezone. Its syntax is to_timestamp(text, text) .


2 Answers

You need to supply a format mask. In PostgreSQL there is no default:

select to_char(1234, 'FM9999'); 

If you don't know how many digits there are, just estimate the maximum:

select to_char(1234, 'FM999999999999999999'); 

If the number has less digits, this won't have any side effects.

If you don't need any formatting (like decimal point, thousands separator) you can also simply cast the value to text:

select 1234::text 
like image 140
a_horse_with_no_name Avatar answered Sep 23 '22 09:09

a_horse_with_no_name


you have to specify a numeric format, ie:

to_char(1234, '9999') 

Take a look here for more info: http://www.postgresql.org/docs/current/static/functions-formatting.html

like image 41
Lorenzo L Avatar answered Sep 25 '22 09:09

Lorenzo L