From number to clearer string

T

* Tong *

Hi,

Is any Perl modules that can translate number like 10987654321 into
clearer to read string 10,987,654,321? and back?

I don't know what this kind of transformation called, so I don't know how
to search. thanks.
 
T

Todd

* Tong * said:
Hi,

Is any Perl modules that can translate number like 10987654321 into
clearer to read string 10,987,654,321? and back?

I don't know what this kind of transformation called, so I don't know how
to search. thanks.

Hmmm, number and commas

what if I try

perldoc -q commas

Found in /apps/perl/5.9.1/lib/5.9.1/pod/perlfaq5.pod
How can I output my numbers with commas added?

This subroutine will add commas to your number:

sub commify {
local $_ = shift;
1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
return $_;
}

This regex from Benjamin Goldberg will add commas to
numbers:

s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g;

It is easier to see with comments:

s/(
^[-+]? # beginning of number.
\d{1,3}? # first digits before first comma
(?= # followed by, (but not included
in the match) :
(?>(?:\d{3})+) # some positive multiple of three
digits.
(?!\d) # an *exact* multiple, not x * 3
+ 1 or whatever.
)
| # or:
\G\d{3} # after the last group, get three
digits
(?=\d) # but they have to have more
digits after them.
)/$1,/xg;
 
P

Paul Lalli

* Tong * said:
Is any Perl modules that can translate number like 10987654321 into
clearer to read string 10,987,654,321? and back?

I don't know what this kind of transformation called, so I don't know how
to search. thanks.

How about the word "commas"?

perldoc -q commas
"How can I output my numbers with commas added?"

(Removing the commas again is a pretty trivial use of the tr///
operator)

Paul Lalli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top