RCR feedback: Numeric#grouped

R

Roger Pack

Hello all.
I notice in ruby there's an easy to way to input "separated" number:

1_000_000
1_000_000.0

But there doesn't seem to be an easy way to "separate" digits when
outputting. At least I'm not aware of any.
The end goal would be something like

print "human readable with commas: #{1_000_000.0.grouped(',')}"

human readable with commas: 1,000,000.0

Does this already exist and, if not, any feedback (method name,
suitability) for its addition?
Thank you!
-r
 
J

John Feminella

Try this:

=3D=3D=3D=3D begin snippet =3D=3D=3D=3D
class Numeric
def separate(sep=3D",")
self.to_s.reverse.scan(/(?:\d*\.)?\d{1,3}-?/).join(sep).reverse
end
end

100.separate
=3D> "100"

100000.separate
=3D> "100,000"

1000000000.separate
=3D> "1,000,000,000"

1000000000.separate('.')
=3D> "1.000.000.000"

10000.12345.separate
=3D> "10,000.12345"
=3D=3D=3D=3D end snippet =3D=3D=3D=3D

~ jf
 
R

Roger Pack

John Feminella wrote in post #980950:
Try this:

==== begin snippet ====
class Numeric
def separate(sep=",")
self.to_s.reverse.scan(/(?:\d*\.)?\d{1,3}-?/).join(sep).reverse
end
end

I like the method name...any feedback on whether or not this should be
in core? (my inclination is yes...)
-r
 
B

Brian Candler

How about supporting extended sprintf syntax? From the manpage:

The five flag characters above are defined in the C standard. =

The
SUSv2 specifies one further flag character.

' For decimal conversion (i, d, u, f, F, g, G) the output is =

to be
grouped with thousands' grouping characters if the locale =

infor=E2=80=90
mation indicates any. Note that many versions of gcc(1) =

cannot
parse this option and will issue a warning. SUSv2 =

does not
include %'F.

i.e. "%'d" % 12345678

-- =

Posted via http://www.ruby-forum.com/.=
 

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

Forum statistics

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

Latest Threads

Top