There may be much easier ways to do this but Science wrote a nice little regular expression which will convert your numbers to comma delimited strings in pure Ruby. It demonstrates some cool features of Ruby from which maybe you will learn!
def comma_numbers(number, delimiter = ',')
number.to_s.reverse.gsub(%r{([0-9]{3}(?=([0-9])))}, “\\1#{delimiter}”).reverse
end
# here are some examples:
puts comma_numbers(1000)
# “1,000″
puts comma_numbers(123456.78)
# “123,456.78″
puts comma_numbers(”$12345″)
# “$12,345″
puts comma_numbers(”123456″, “.”)
# “123.456″ # Euro-friendly!
Let’s take a look at how this thing works. There are a couple of items that are worth examining in a little detail..
Firstly, since Regex operates left to right but we want to sub out numbers from right to left, we first reverse the string, which is super easy with a Ruby string.
Secondly, we create a regex pattern that does something interesting. We want to match and replace any three numbers which have a number in front of them with those same three numbers plus a comma. The interesting bit is that if we aren’t careful when we match the number in front of our three numbers, we will “advance the search pointer” inside regex past that value. This will result in our search being “off by one” - creating conversions such as “1,1234,000″
To understand why, first remember that the string is reversed when we regex it: “0004321″ Next, consider that the “4″ in the above example - it will be matched by a regex of %{([0-9]{3})[0-9]} We need to reference it to ensure that commas are only placed when there is a number in front of our block of three numbers..
But we want to search that 4 “again” after a match is made by gsub, so it can be counted as the group of three digits”234″ to be comma’ed. So we use a nice little Ruby extension to regex (?=[x]) which lets you match something in a repeated regex but keep the search from considering it matched for future matches. This yields the regex of %r{([0-9]{3}(?=([0-9])))} - some of those parens are extraneous but it’s easier for Science to read it that way (and future legibility of regex is one of its crucial failings). Happy commas!