Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL convert a string with commas into an integer

Tags:

postgresql

I want to convert a column of type "character varying" that has integers with commas to a regular integer column.

I want to support numbers from '1' to '10,000,000'.

I've tried to use: to_number(fieldname, '999G999G999'), but it only works if the format matches the exact length of the string.

Is there a way to do this that supports from '1' to '10,000,000'?

like image 303
Aaron Kreider Avatar asked Sep 18 '13 21:09

Aaron Kreider


People also ask

How do I convert text to integer in PostgreSQL?

The PostgreSQL TO_NUMBER() function converts a character string to a numeric value.

How do I cast an expression in PostgreSQL?

PostgreSQL supports a CAST operator that is used to convert a value of one type to another. Syntax: CAST ( expression AS target_type ); Let's analyze the above syntax: First, specify an expression that can be a constant, a table column, an expression that evaluates to a value.

What is Smallint in Postgres?

PostgreSQL allows a type of integer type namely SMALLINT . It requires 2 bytes of storage size and can store integers in the range of -37, 767 to 32, 767. It comes in handy for storing data like the age of people, the number of pages in a book, etc. Syntax: variable_name SMALLINT.

What is the difference between numeric and integer in PostgreSQL?

As opposed to INTEGER and BIGINT data types that can store only whole numbers, the DECIMAL and NUMERIC data types can store rational numbers. They can store 13,1072 digits before the decimal point and up to 16,383 digits after the decimal point.


1 Answers

select replace(fieldname,',','')::numeric ;

To do it the way you originally attempted, which is not advised:

select to_number( fieldname,
                  regexp_replace( replace(fieldname,',','G') , '[0-9]' ,'9','g')
                );

The inner replace changes commas to G. The outer replace changes numbers to 9. This does not factor in decimal or negative numbers.

like image 152
vol7ron Avatar answered Oct 11 '22 15:10

vol7ron