user1946705 user1946705 - 2 years ago 60
Ruby Question

How to format a number 1000 as "1 000"

I need a way to format numbers. I stored some numbers in my DB table, e.g.

, and would like to print them in this format
12 500
(so there is a space every 3 digits). Is there an elegant way to do this?

Answer Source


there is no built in way to it ( unless you using Rails, ActiveSupport Does have methods to do this) but you can use a Regex like

formatted_n = n.to_s.reverse.gsub(/...(?=.)/,'\&,').reverse
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download