Skip to content

Instantly share code, notes, and snippets.

@apeiros
Last active November 5, 2015 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apeiros/9d3c8b1fcff9d1769569 to your computer and use it in GitHub Desktop.
Save apeiros/9d3c8b1fcff9d1769569 to your computer and use it in GitHub Desktop.
localize a number (thousands and decimal separator)
class Numeric
# Localize a number, adding thousands and decimals separators and setting the
# number of decimals
#
# @example
# 1234.56.localize # => "1,234.56"
# 1234.56.localize(thousands: "'", decimal: ",", places: 4) # => "1'234,5600"
def localize(thousands: ',', decimal: '.', places: nil)
raise ArgumentError, "decimal must be set" unless decimal
raise ArgumentError, "thousands and decimal must be different" if thousands == decimal
number = places ? sprintf("%.*f", places, self) : to_s
integer, decimals = *number.split(".")
integer.gsub!(/(\d)(?=\d{3}+$)/, "\\1#{thousands}")
decimals ? "#{integer}#{decimal}#{decimals}" : integer
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment