1

I tried to sum two floating point numbers. When I use "." as the delimiter between decimals, it works correctly. But, when I use a comma, the last two numbers return zero. Example:

puts "Type the first number:"
firstNum = gets.to_f # I typed 55,11

puts "Type the second number:"
secondNum = gets.to_f # I typed 45,44

result = firstNum +  secondNum

puts sprintf('%.2f', result)  # Return 100.00

If I use "." to separate the numbers, the return is 100.55.

sawa
  • 165,429
  • 45
  • 277
  • 381
Gustavo Dias
  • 3,811
  • 3
  • 11
  • 6

1 Answers1

2

Fixnum#to_f expects dots. To allow commas you should do convert them to commas explicitly:

puts "Type the first number:"
#               ⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓
firstNum = gets.tr(',', '.').to_f # I typed 55,11

puts "Type the second number:"
#                ⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓
secondNum = gets.tr(',', '.').to_f # I typed 45,44

result = firstNum +  secondNum

puts sprintf('%.2f', result)  # Return 100.55
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160