DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Add Thousands Separators To Numbers

09.09.2005
| 17878 views |
  • submit to reddit
        I've finally figured out how to add thousands separators.

If there's a built in for this (like a `sprintf` parameters) I don't want to hear it.  I just don't, ok?

def ts( st )
  st = st.reverse
  r = ""
  max = if st[-1].chr == '-'
    st.size - 1
  else
    st.size
  end
  if st.to_i == st.to_f
    1.upto(st.size) {|i| r << st[i-1].chr ; r << ',' if i%3 == 0 and i < max}
  else
    start = nil
    1.upto(st.size) {|i|
      r << st[i-1].chr
      start = 0 if r[-1].chr == '.' and not start
      if start
        r << ',' if start % 3 == 0 and start != 0  and i < max
        start += 1
      end
    }
  end
  r.reverse
end

That's it.

puts ts('100')
puts ts('1')
puts ts('1000')
puts ts('1000000.01')
puts ts('100046546510000.022435451')
puts ts('-100')
puts ts('-1')
puts ts('-1000')
puts ts('-1000000.01')
puts ts('-100046546510000.022435451')

outputs:

100
1
1,000
1,000,000.01
100,046,546,510,000.022435451
-100
-1
-1,000
-1,000,000.01
-100,046,546,510,000.022435451

It's ugly, yeah, but it works.    

Comments

Snippets Manager replied on Tue, 2010/12/28 - 5:40pm

number_with_delimiter(12345678) # => 12,345,678 http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_delimiter

Snippets Manager replied on Mon, 2012/05/07 - 2:14pm

http://www.rubygarden.org/ruby?NumericFormat

Snippets Manager replied on Mon, 2012/05/07 - 2:14pm

Regex to the rescue: def ts(st) st.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1,") end