Created
March 7, 2013 08:21
-
-
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.
This file contains 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
def separate_comma(number) | |
number.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse | |
end |
This file contains 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
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