Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@CarlosCD
Last active December 27, 2015 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CarlosCD/7376440 to your computer and use it in GitHub Desktop.
Save CarlosCD/7376440 to your computer and use it in GitHub Desktop.
Get a string that is the decimal representation of that number grouped by commas after every 3 digits. Like 1000 #=> '1,000'. --See the issues with some edge cases for floats.
# General case, English notation:
def pretty_number(num)
num.to_s.tap do |s|
:anything while s.gsub!(/^([^.]*)(\d)(?=(\d{3})+)/, "\\1\\2,")
end
end
# Puts the commas in the thousands, allows to use a character other than ',':
def pretty_number(number, comma = ',')
number.to_s.tap do |s|
:recursive_horror while s.gsub!(/^([^.]*)(\d)(?=(\d{3})+)/, "\\1\\2#{comma}")
end
end
# Allows to use characters other than comma and dots:
def pretty_number(number, comma = ',', dot = '.')
number.to_s.gsub('.', dot).tap do |s|
false while s.gsub!(/^([^#{dot}]*)(\d)(?=(\d{3})+)/, "\\1\\2#{comma}")
end
end
# For example, in the US:
pretty_number 1000_000.55
#=> "100,000.5"
# In Spain:
pretty_number 1000_000.55, '.', ','
=> "1.000.000,55"
# Known issues
# 1. Float#to_s could be represented with an exponential value, which would derail the
# whole conversion. So proceed with care:
number = 23232423423442300000.334 #=> 2.32324234234423e+19
pretty_number number #=> "2.32324234234423e+19"
# 2. Floats with many decimals would get an approximate value. Using BigDecimal would
# require a different approach (check the class of then parameter), but that could be
# a good way to go
number = 23232423423442300000.334 #=> 2.32324234234423e+19
number.to_i #=> 23232423423442300928
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment