Ruby – Troubleshooting Division Issues

ruby

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?

Best Answer

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
Related Question