Never been to DZone Snippets before?

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

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

add thousands separators to numbers

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.

Python Comma Separated

Separate a list of string in english-language list fashion, just like the Ruby snippet listed earlier.

def textList(listtext, sep1=', ', sep2=', and '):
        return (len(listtext) > 1 
        and ("%s%s%s" % (sep1.join(listtext[:-1]), sep2, listtext[-1])) 
        or listtext[0])


['one'] -> "one"
['one', 'two', 'three'] -> "one, two, and three"
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS