I cannot for the life of me figure out why dividing isn't working in this Aslsx export. I can add, subtract, multiple and do modulus division fine, but when I try to do answer_number / question_number
it is always coming out as 0. Any ideas what I'm doing wrong?
Works spitting out the answer_number
times the question_number
:
@survey.questions.each do |question|
question_number = Choice.where(question_id: question.id).length
question.answers.each do |answer|
answer_number = Choice.where(answer_id: answer.id).length
sheet.add_row [answer_number, question_number, answer_number * question_number]
end
end
Doesn't work - spits out 0:
@survey.questions.each do |question|
question_number = Choice.where(question_id: question.id).length
question.answers.each do |answer|
answer_number = Choice.where(answer_id: answer.id).length
sheet.add_row [answer_number, question_number, answer_number / question_number]
end
end
I also thought that maybe it was doing some sort of rounding down when the number was less than 0, but this doesn't seem to work either (the end goal is to get the percent of each answer chosen):
@survey.questions.each do |question|
question_number = Choice.where(question_id: question.id).length
question.answers.each do |answer|
answer_number = Choice.where(answer_id: answer.id).length
sheet.add_row [answer_number, question_number, answer_number / question_number * 100]
end
end
Since both numbers are integers, ruby is doing integer division, which ignores remaining fractions, and I would guess all your divisions are returning numbers between 0 and 1, so the answer is always 0, to avoid that one of the both numbers should be a float so like @mtm suggested, add a to_f
function to either of the numbers