From: Gregory Millam Date: 2003-12-09T04:49:07+09:00 Subject: Re: format money Received: Tue, 9 Dec 2003 04:37:54 +0900 And lo Peter wrote: > > Yes, there is. I'm sure that there's a module in the RAA for this, > > although I can't find it at the moment. It's not too hard to do manually, > > though: > > > > irb(main):001:0> balance = 2111000.5756 > > => 2111000.5756 > > irb(main):002:0> balance = (balance * 100).round/100.0 > > => 2111000.58 > > irb(main):003:0> balance.to_s.reverse.gsub(/\d{3}/, '\&,').reverse > > => "2,111,000.58" > > This would turn 111000.5756 into ,111,000.58 > I assume that's not the intention? > # Here's my try: balance.to_s.reverse.gsub(/(\d{3})(?=\d)/,'\1,').reverse examples: irb(main):007:0> "123456789".reverse.gsub(/(\d{3})(?=\d)/,'\1,').reverse => "123,456,789" irb(main):008:0> "1234567890".reverse.gsub(/(\d{3})(?=\d)/,'\1,').reverse => "1,234,567,890" (?=\d) is a lookahead assertion that checks to see if there's a digit ahead of the current pattern without capturing it (which is the important thing). - Greg Millam