Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Refuses to Divide Correctly

Tags:

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?

like image 511
RyanScottLewis Avatar asked Sep 19 '09 07:09

RyanScottLewis


People also ask

How do you round up in Ruby?

The round() method can be used to round a number to a specified number of decimal places in Ruby. We can use it without a parameter ( round() ) or with a parameter ( round(n) ). n here means the number of decimal places to round it to.


2 Answers

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
like image 130
Matthew Scharley Avatar answered Nov 11 '22 06:11

Matthew Scharley


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
like image 41
Daniel Pryden Avatar answered Nov 11 '22 06:11

Daniel Pryden