How do I make a variable have a float value in Ruby?

Asked 2 years ago, Updated 2 years ago, 128 views

total_a = 10
total_b = 5
ratio = total_b/total_a

print ratio

If you do this, the ratio becomes 0. It seems to be processed automatically in an integer type, so how do I make the ratio have a value of 0.5?

ruby double

2022-09-22 21:15

1 Answers

Try multiplying by total_b.to_f or by 1.0 when calculating the ratio. It automatically converts the type.

total_a = 10
total_b = 5
ratio = total_b.to_f / total_a
# # ratio = 1.0 * total_b/total_a

print ratio


2022-09-22 21:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.