Skip to content

Instantly share code, notes, and snippets.

@jkaihsu
Created March 7, 2013 08:21
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 jkaihsu/5106422 to your computer and use it in GitHub Desktop.
Save jkaihsu/5106422 to your computer and use it in GitHub Desktop.
Write a method separate_comma which takes an integer as its input and returns a comma-separated integer as a string.
def separate_comma(number)
number.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse
end
def separate_comma(number)
array = number.to_s.reverse.split(//)
len = array.length
if len<=6
n = 0
elsif len%2 == 0
n = 1
else
n = 2
end
if len < 4
return array.join.reverse.to_s
else
i = 3
while i < len+n do
array.insert(i, ',')
i += 4
end
end
return array.join.reverse.to_s
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment