Slightly OT - Ruby division


#1

Hey all,

In my code, it seems that when I divide two integers, the result is an
integer. Is there any way to make it such that when I divide two
integers,
the result is a double?

Any help appreciated,

Jin


#2

Jin L. wrote:

Hey all,

In my code, it seems that when I divide two integers, the result is an
integer. Is there any way to make it such that when I divide two
integers,
the result is a double?

No, you have to convert one of them to a float first:
x.to_f/y


#3

int1 / int2.to_f

this will force it into a float.


#4

On 16/12/2005, at 11:27 AM, Jin L. wrote:

In my code, it seems that when I divide two integers, the result is
an integer. Is there any way to make it such that when I divide two
integers, the result is a double?

Ruby never automatically casts (except between Fixnum and Bignum), so
you have to cast to float using Fixnum#to_f

1.to_f / 5.to_f # => 0.2


Phillip H.
removed_email_address@domain.invalid


#5

On 12/15/05, Jin L. removed_email_address@domain.invalid wrote:

Hey all,

In my code, it seems that when I divide two integers, the result is an
integer. Is there any way to make it such that when I divide two integers,
the result is a double?

a = 10
b = 3
a/b.to_f

-Matt


#6

On 12/16/05, Jin L. removed_email_address@domain.invalid wrote:

Hey all,

In my code, it seems that when I divide two integers, the result is an
integer. Is there any way to make it such that when I divide two integers,
the result is a double?

Any help appreciated,

irb(main):001:0> 5/3
=> 1
irb(main):002:0> 5.to_f/3
=> 1.66666666666667
irb(main):003:0> 5*1.0/3
=> 1.66666666666667

martin


#7

This might help:

a = 1
=> 1

b = 2
=> 2

a / b
=> 0

a.to_f / b
=> 0.5

a / b.to_f
=> 0.5

a.to_f / b.to_f
=> 0.5

Regards,
Douglas


#8

Jin L. <jinslee@…> writes:

Hey all,
In my code, it seems that when I divide two integers, the result is an
integer. Is there any way to make it such that when I divide two
integers, the result is a double?
Any help appreciated,
Jin

Apparently Float is not only a class, but also a method! I gather, then,
that
Ruby is sort of Lisp-2 (non-methods and methods have different
namespaces).

#> Float(3)
3.0
#> Float(22)/7
3.14285714285714


#9

Apparently Float is not only a class, but also a method! I gather, then, that
Ruby is sort of Lisp-2 (non-methods and methods have different namespaces).

#> Float(3)
3.0
#> Float(22)/7
3.14285714285714

#to_f is usually used instead:

#> 3.to_f
3.0
#> 22.to_f / 7

3.14285714285714


rick
http://techno-weenie.net