Carefully take the pitfalls of division from the beginning. Let's take Ruby as an example. The introduction and explanation are very long. The conclusion is [here](using the #to_f method).
For example, suppose you want to do "80 ÷ 100". The expected answer is "0.8" (or an equal number) ...
80 / 100
=> 0
0 will be returned. Why?
This is because the previous calculation is considered to be an "integer-to-integer calculation". I think "integers are mutual", but integer and integer calculations only return integers.
For example, "101 ÷ 100" is also the same. I would like you to return "1.01" as the answer, but it will be as follows.
101 / 100
=> 1
To get the answer you expect, you need to include a small number of digits in the calculation. You have to say, "Calculate as a decimal, not as an integer!" It is necessary to be aware that these are different in the program even for calculations that you do not pay particular attention to on a daily basis.
For example, you can tell that a small number of digits are in the calculation by writing:
80.0 / 100
=> 0.8
You can write
80 / 100.0
=> 0.8
You can write, of course
80.0 / 100.0
=> 0.8
But it's good.
I see. But what if this is a variable? I would like to know the following method to handle such a situation.
The to_f
method can be used when you want to treat it as a" decimal "in Ruby. "F" means "f" of float, "floating point number". (This is also a unique concept, but there are many articles that you can refer to, so I will give it to you.)
Now, how to use it, just add to_f
after the numerical value (variable is OK).
80.to_f / 100
=> 0.8
You can write
80 / 100.to_f
=> 0.8
You can write, of course
80.to_f / 100.to_f
=> 0.8
But it's good.
With this method, it is okay if variables come in.
n = 80
n.to_f / 100
=> 0.8
You've got the results you expected.
Recommended Posts