like in C and C++
double x
How to do it in ruby ?
Or to be in the type float?
I want to run
x=5/2
then
x=2.5
instead of
x=2
like in C and C++
double x
How to do it in ruby ?
Or to be in the type float?
I want to run
x=5/2
then
x=2.5
instead of
x=2
If at least one of the operands is a float, the result will be a float too.
5 / 2.0 # => 2.5
In ruby, you create a float by specifying a decimal point:
2 #=> integer
2.0 #=> float
If you divide an integer by another integer, you get an integer. You have to use a float in the division:
5 / 2 #=> 2
5.0 / 2 #=> 2.5
5 / 2.0 #=> 2.5
Ruby is dynamically typed, so there isn't an explicit way to cast a variable to a specific type. Eg:
a = "a" # here a is a String
a = 5 # now a is a Fixnum
a = 5.0 # now a is a Float
is totally valid.
So what happens when you say 5/2
? Ruby looks up the /
operator in the first operand, in this case an integer, and then calls the function with the second operand, also an integer. Thus Ruby assumes you want integer division.
The solution is to make one of the operators a float, this can be done in at least two ways:
5 / 2.0
or
5 / 2.to_f
Variables don't have types in Ruby, only objects do. (And the concept of "type" is latent, it is not manifest in the program. The "type" of an object is the protocol it speaks, i.e. the messages it responds to and how it responds to those messages. In particular, the type of an object is not its class.)
By default in ruby all the floats are double according to the source code
To create a float value you have to add .0 to difference from the integers value.
Note: if you use two integers in a one operation by default the result is an integer
5.0 # float
5 # integer
5 / 2 = 2 # integer
5 / 2.0 = 2.5 #float
Float definition on the ruby source code