Tuesday, June 9, 2009

Perl Number formating using Regexp


Share at Facebook

Using a single regex you can easily convert a number like 1234567890 into 1,234,567,890. I don't what this call, that's why I was put the title is number formatting. Here goes the regular expression with example.

my $number = 1234567890;
$number =~ s/(\d)(?=(\d{3})+(\D|$))/$1\,/g;
print $number;

Output : 1,234,567,890


The above regex just takes the digits from last, or three digits just before the comma, and if another extra digit exist without those three, it just push a comma inside. This will make one digit goes to left side, and other three digits goes to right side.

Just a simple regexp made your life easier to do such kind of conversion.




No comments: