RyanScottLewis
RyanScottLewis

Reputation: 14016

Ruby Refuses to Divide Correctly

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?

Upvotes: 12

Views: 8435

Answers (2)

Daniel Pryden
Daniel Pryden

Reputation: 60947

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

Upvotes: 9

Matthew Scharley
Matthew Scharley

Reputation: 132244

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

Upvotes: 28

Related Questions