Last active
August 29, 2015 14:21
-
-
Save gilcierweb/c9c640f8f4eb051d0988 to your computer and use it in GitHub Desktop.
Function format number Ruby
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
#number.rb | |
puts 'Informe um número' | |
number = gets.chomp | |
def format_number(number) | |
for num in 0..number.to_i | |
puts num.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse | |
end | |
end | |
format_number(number) | |
def format_with_separator(number) | |
whole_part, decimal_part = number.to_s.split('.') | |
[whole_part.gsub(/(\d)(?=\d{3}+$)/, '\1,'), decimal_part].compact.join('.') | |
end | |
puts '--------' | |
puts format_with_separator(number) | |
puts '--------' | |
puts sprintf("%0.2f", number).gsub(/(\d)(?=\d{3}+\.)/, '\1,') | |
puts '--------' | |
puts sprintf("%d", number).gsub(/(\d)(?=\d{3}+$)/, '\1,') | |
puts '--------' | |
puts number.gsub(/[^\d\.]/, '') | |
#Use in terminal | |
#ruby number.rb |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment