Over a million developers have joined DZone.

Format number with thousands separator

DZone's Guide to

Format number with thousands separator

· ·
Free Resource

This gsub call provides a concise way to add thousands separators to numeric values. If you know what kinds of numbers you expect, you can simplify this even more, but for public consumption, I wanted to allow for both integers and decimal numbers of any kind.

As another example, if you're actually formatting currencies, and know you always want two decimal places, you can simply use

sprintf("%0.2f", number).gsub(/(\d)(?=\d{3}+\.)/, '\1,')

If you were formatting with no decimal places, you would use `$` or `\Z` instead of the `\.`, like

sprintf("%d", number).gsub(/(\d)(?=\d{3}+$)/, '\1,')
def format_with_separator(number)
  whole_part, decimal_part = number.to_s.split('.')
  [whole_part.gsub(/(\d)(?=\d{3}+$)/, '\1,'), decimal_part].compact.join('.')

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}