Possible Duplicate:
Ruby Refuses to Divide Correctly
I am using Ruby on Rails 3.2.2 and when I try to calculate 10 * (50 / 100) I got back 0 but when I make 10 * 50 / 100 I got back 5.
For technical reasons, I can not use the latter since my code is like the following:
perc = 50 /100
# Some code that uses the 'perc' variable
... = method_name(perc)
return 10 * perc
What should I make to solve the problem and have 5 (not 5.0 or something else; that is, so that the returns is an Integer)?
50 / 100 is 0 because you are using integer division. The result is truncated to an integer.
Performing the multiplication first works because then the division gives a whole number.
You could perform the calculation using floats instead of integers: 50.0 / 100.0 == 0.5, then round the result to an integer at the end of the calculation.
See it working online: ideone