tags:

views:

172

answers:

2

I'm simply trying to get a percentage.

irb(main):001:0> (25 / 50) * 100
=> 0

This should most definitely equal 50, as confirmed by my calculator (copied and pasted the same equation into gcalc). Why does Ruby refuse to do this?

+8  A: 

It's doing integer division.

Basically, 25 is an integer (a whole number) and so is 50, so when you divide one by the other, it gives you another integer.

25 / 50 * 100 = 0.5 * 100 = 0 * 100 = 0

The better way to do it is to first multiply, then divide.

25 * 100 / 50 = 2500 / 50 = 50

You can also use floating point arithmetic explicitly by specifying a decimal point as in:

25.0 / 50.0 * 100 = 0.5 * 100 = 50
Matthew Scharley
Thanks guys! I was calculating the percentage completed of opening a file in open-uri. Here's what I used: percent = (file_downloaded.to_f/file_length.to_f) * 100
c00lryguy
Use the second form then. It's easier than trying to convert to floating point numbers.
Matthew Scharley
Or rather, the first solution. The multiply then divide one. You know what I mean.
Matthew Scharley
+2  A: 

Because you're dividing an integer by an integer, so the result is getting truncated to integer (0.5 -> 0) before getting multiplied by 100.

But this works:

>> (25 / 50) * 100
=> 0
>> (25.0 / 50) * 100
=> 50.0
Daniel Pryden