Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find remainder of a division in Ruby?

Tags:

math

ruby

I'm trying to get the remainder of a division using Ruby.

Let's say we're trying to divide 208 by 11.

The final should be "18 with a remainder of 10"...what I ultimately need is that 10.

Here's what I've got so far, but it chokes in this use case (saying the remainder is 0).

division = 208.to_f / 11 rounded = (division*10).ceil/10.0 remainder = rounded.round(1).to_s.last.to_i 
like image 826
Shpigford Avatar asked Jan 31 '12 20:01

Shpigford


People also ask

What does '%' mean in Ruby?

It gives the remainder when counter is divided by 2. For example: 3 % 2 == 1 2 % 2 == 0.

What operator can you use on an integer to compute the remainder of its Euclidean division by any number in Ruby?

The modulo operator gives you the remaining of a division.


2 Answers

The modulo operator:

> 208 % 11 => 10 
like image 62
Josh Lee Avatar answered Sep 28 '22 23:09

Josh Lee


If you need just the integer portion, use integers with the / operator, or the Numeric#div method:

quotient = 208 / 11 #=> 18  quotient = 208.0.div 11 #=> 18 

If you need just the remainder, use the % operator or the Numeric#modulo method:

modulus = 208 % 11 #=> 10  modulus = 208.0.modulo 11 #=> 10.0 

If you need both, use the Numeric#divmod method. This even works if either the receiver or argument is a float:

quotient, modulus = 208.divmod(11) #=> [18, 10]  208.0.divmod(11) #=> [18, 10.0]  208.divmod(11.0) #=> [18, 10.0] 

Also of interest is the Numeric#remainder method. The differences between all of these can be seen in the documentation for divmod.

like image 26
Phrogz Avatar answered Sep 28 '22 23:09

Phrogz