Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"wrong number of arguments" ArgumentError when using round

Tags:

rounding

ruby

I am trying to convert a temperature from Fahrenheit to Celsius:

puts 'Convertir grados Fahrenheit a Celcius'
STDOUT.flush
x = gets.chomp

aprox = (x * 100.0).round(2) / 100.0

resultado = (aprox-32)/1.8

puts resultado

I use the correct formula for converting Fahrenheit to Celcius:

Celsius = Fahrenheit - 32 / 1.8

However, when I run this in the console, it gives me the following error:

`round': wrong number of arguments (1 for 0) (ArgumentError)

I've tried different things but I don't understand why this doesn't work.

like image 559
Ivanhercaz Avatar asked Oct 12 '10 17:10

Ivanhercaz


3 Answers

In ruby version prior to 1.9.0 round does not take arguments. It rounds to the nearest integer (see the documentation about floats and the use of round)

Use this instead:

aprox = (x * 100).round() / 100.0

The whole point of multiplying and dividing by 100 is to round the last two digit of x.

like image 128
Pierre-Luc Simard Avatar answered Oct 11 '22 23:10

Pierre-Luc Simard


You don't specify what version of Ruby you are using. That makes a difference, because in Rubies prior to 1.9 Float#round did not take a parameter. In 1.9+ it does.

>> RUBY_VERSION #=> "1.9.2"
>> pi = 3.141 #=> 3.141
>> pi.round #=> 3
>> pi.round(1) #=> 3.1
>> 3.141.round(1) #=> 3.1
like image 28
the Tin Man Avatar answered Oct 11 '22 22:10

the Tin Man


activesupport (part of rails) also gives you Float#round(precision)

like image 2
rogerdpack Avatar answered Oct 11 '22 21:10

rogerdpack