Divide by Ruby! Why is it 0?

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).

Be careful when the number of answers is small

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?

What is a program?

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

How do you calculate?

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.

use to_f method

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

Divide by Ruby! Why is it 0?
Is it OutOfMemoryError?
Why Schools Learn Ruby
Why preventDefault is needed
[Ruby] What is true?
[Ruby on Rails] Understand why Set # include? Is so fast
What is docker run -it?
[Summary] Why make it object-oriented?
What is a Ruby module?
Is Ruby all objects, true?
Ruby # {} is not variable expansion
It was given by render
Why Kotlin is so useful
[Ruby] What is `!!` used for?
[Ruby] What is an instance?
Is it an Android app?
[Ruby] Why require'json'to enable to_json
[For beginners] Ruby is said to be ruby, but what about it?
[Rails] Why is it render if save is successful and redirect_to fails?