Function to separate every three digits with a comma

Moderator: NorbertKrupa

Post Reply
rajasekhart
Intermediate
Intermediate
Posts: 87
Joined: Wed Apr 25, 2012 8:10 am

Function to separate every three digits with a comma

Post by rajasekhart » Thu Nov 22, 2012 10:35 am

Hi,

I need to write a User Defined Function to separate every three digits of a number with a comma from the right hand side..

Eg: i will pass a number 1234567890 as a parameter to the function.

and i need the result as 1,234,567,890 .

Please help me..


Thanks ,
Raj!!
Rajasekhar.T|HP ATP Vertica Big Data Solutions V1

User avatar
JimKnicely
Site Admin
Site Admin
Posts: 1825
Joined: Sat Jan 21, 2012 4:58 am
Contact:

Re: Function to separate every three digits with a comma

Post by JimKnicely » Fri Nov 23, 2012 3:25 pm

Raj,

Can't you simply use the TO_CHAR function? Something like this:

Code: Select all

dbadmin=> SELECT TO_CHAR(1234567890, '999,999,999,999,999,999,999,999');
             TO_CHAR
----------------------------------
                    1,234,567,890
(1 row)
Jim Knicely

Image

Note: I work for Vertica. My views, opinions, and thoughts expressed here do not represent those of my employer.

id10t
GURU
GURU
Posts: 732
Joined: Mon Apr 16, 2012 2:44 pm

Re: Function to separate every three digits with a comma

Post by id10t » Fri Nov 23, 2012 4:56 pm

Hi!

IMHO - from performance and safety view it's a best solution(I mean Jim's solution).
It can be done with "REGEXP look behind" or UDF(simple loop over number as string from end), but if REGEXP - performance will impact, if UDF - performance and safety.

id10t
GURU
GURU
Posts: 732
Joined: Mon Apr 16, 2012 2:44 pm

Re: Function to separate every three digits with a comma

Post by id10t » Sun Nov 25, 2012 2:43 pm

UPDATE

RegExp solution:(ugly solution)

REGEXP itself: (?<=\d)(?=(\d{3})+(?!\d))

Example:

Code: Select all

dbadmin=> select regexp_replace(54638297869873276253625346125::varchar,'(?<=\d)(?=(\d{3})+(?!\d))',',');
             regexp_replace             
----------------------------------------
 54,638,297,869,873,276,253,625,346,125
(1 row)

Post Reply

Return to “Vertica Database Development”