I need a way to format numbers. I stored some numbers in my DB table, e.g. 12500
, and would like to print them in this format 12 500
(so there is a
The official document suggests three different ways:
1) Using lookbehind and lookahead (Requires oniguruma)
12500.to_s.gsub(/(?<=\d)(?=(?:\d{3})+\z)/, ' ')
# => "12 500"
2) Using only lookahead. Identical to steenslag's answer.
3) Using neither lookahead nor lookbehind
s = 12500.to_s
nil while s.sub!(/(.*\d)(\d{3})/, '\1 \2')
s # => "12 500"