Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Add Thousands Separators To Numbers

DZone's Guide to

Add Thousands Separators To Numbers

·
Free Resource
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.
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}