"Mark J. Reed" <markjreed / mail.com> schrieb im Newsbeitrag news:20030805150600.GD28141 / mulan.thereeds.org... > On Tue, Aug 05, 2003 at 11:55:12PM +0900, Chris Morris wrote: > > I'm brain dead and just trying to get formatted numbers in a task that's > > already 10 tangents deep -- argh. Anyway, how can I sprintf (or > > otherwise) this: > > > > 456778904 > > > > to this: > > > > 456,778,904 > > Unless there's something I don't know about - a distinct possibility > - there's no built-in function to do this. You can, however, > do it with a regex. Assuming the numbers are all integers (no > decimal points), then this will work: > > formatted_n = n.to_s.reverse.gsub(/...(?=.)/,'\&,').reverse This fails for negative numbers in the range -100..-999 and all other negative numbers with an amount of digits that is divisable by 3. Alternative: def format(num) s = num.to_s if s.include? ?. pre, post = s.split '.' "#{pre.reverse.gsub( /\d{3}(?=\d)/, '\&,' ).reverse}.#{post}" else s.reverse.gsub( /\d{3}(?=\d)/, '\&,' ).reverse end end robert