How to format a number 1000 as "1 000" How to format a number 1000 as "1 000" ruby ruby

How to format a number 1000 as "1 000"


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


Activesupport uses this regexp (and no reverse reverse).

10000000.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1 ") #=> "10 000 000"


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(",").reversenumber            #=> 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.