Section 5.7. Working with Very Large Integers


5.6. Formatting Numbers with Commas

There may be better ways to do it, but this one works. We reverse the string to make it easier to do global substitution and then reverse it again at the end:

def commas(x)   str = x.to_s.reverse   str.gsub!(/([0-9]{3})/,"\\1,")   str.gsub(/,$/,"").reverse end puts commas(123)        # "123" puts commas(1234)       # "1,234" puts commas(12345)      # "12,435" puts commas(123456)     # "123,456" puts commas(1234567)    # "1,234,567"





The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net