How to format a number 1000 as "1 000"
Solution 1
see: http://www.justskins.com/forums/format-number-with-comma-37369.html
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
Solution 2
Activesupport uses this regexp (and no reverse reverse).
10000000.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1 ") #=> "10 000 000"
Solution 3
Here's another method that is fairly clean and straightforward if you are dealing with integers:
number.to_s.reverse.scan(/\d{1,3}/).join(",").reverse
number #=> 12345678
.to_s #=> "12345678"
.reverse #=> "87654321"
.scan(/\d{1,3}/) #=> ["876","543","21"]
.join(",") #=> "876,543,21"
.reverse #=> "12,345,678"
Works great for integers. Of course, this particular example will separate the number by commas, but switching to spaces or any other separator is as simple as replacing the parameter in the join
method.
Solution 4
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"
Solution 5
very simple:
number_with_delimiter(12500, delimiter: " ")
see: http://apidock.com/rails/ActionView/Helpers/NumberHelper/number_with_delimiter
user1946705
Updated on June 06, 2022Comments
-
user1946705 almost 2 years
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 format12 500
(so there is a space every 3 digits). Is there an elegant way to do this?