Forum: Ruby RCR feedback: Numeric#grouped

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bec38d63650c8912b6ba9b557fb953b9?d=identicon&s=25 Roger Pack (rogerdpack)
on 2011-02-10 20:59
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
74283a8aa16c958f3d48d41d96c99577?d=identicon&s=25 John Feminella (Guest)
on 2011-02-10 21:36
(Received via mailing list)
Try this:

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

100.separate
 => "100"

100000.separate
 => "100,000"

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

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

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

~ jf
--
John Feminella
Principal Consultant, BitsBuilder
LI: http://www.linkedin.com/in/johnxf
SO: http://stackoverflow.com/users/75170/
Bec38d63650c8912b6ba9b557fb953b9?d=identicon&s=25 Roger Pack (rogerdpack)
on 2011-02-11 17:33
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
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (candlerb)
on 2011-02-12 11:40
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ā€
              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
This topic is locked and can not be replied to.