Format Currency

Format a number as currency with the appropriate symbol and separators.

Code

Utilities
symbols = {'USD' => '$', 'EUR' => '€', 'GBP' => '£', 'JPY' => '¥'}
symbol = symbols[currency] || currency
formatted = num.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse
parts = formatted.split('.')
parts[1] = parts[1].to_s.ljust(2, '0')[0, 2]
return "#{symbol}#{parts.join('.')}"

Parameters

The number to format.

Currency code (USD, EUR, GBP, etc.).

Locale for formatting.

Server

More Ruby Snippets