I can’t figure out why a calculation is wrong. I’m trying to calculate the percent of time that the user scores over the median score in my Rails app.
controller
my_scores_over_median_count = 6
total_scores_over_median = 8
@my_over_median_percent = (my_scores_over_median_count / total_scores_over_median) * 100
When I add this to my controller:
puts my_scores_over_median_count
puts total_scores_over_median
puts @my_over_median_percent
I get:
6 (correct)
8 (correct)
0 (incorrect)
Can someone please help me understand why I’m getting 0 instead of 75 ? Thank you.
classic integer division problem. Change it to this and see it work:
Ruby interprets 6 as a ‘Fixnum’ class, essentially an integer. We know this by:
Dividing any number by a Fixnum causes Ruby to do integer math which means any remainder gets thrown out. So:
If you have a variable that is a Fixnum, and you want to convert it to a float to force floating point division, you use the .to_f method: