Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.