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
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.






Comments
Snippets Manager replied on Tue, 2010/12/28 - 5:40pm
Snippets Manager replied on Mon, 2012/05/07 - 2:14pm
Snippets Manager replied on Mon, 2012/05/07 - 2:14pm
def ts(st) st.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1,") end