Last active
November 5, 2015 19:55
-
-
Save apeiros/9d3c8b1fcff9d1769569 to your computer and use it in GitHub Desktop.
localize a number (thousands and decimal separator)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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