3

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
Tom Hammond
  • 5,842
  • 12
  • 52
  • 95
  • possible duplicate of [Why is division in Ruby returning an integer instead of decimal value?](http://stackoverflow.com/questions/5502761/why-is-division-in-ruby-returning-an-integer-instead-of-decimal-value) – Matt Sep 10 '14 at 14:48
  • 2
    You need a float... `answer_number.to_f` – Matt Sep 10 '14 at 14:49
  • Yep. I'm an idiot. I knew it was something easy :) – Tom Hammond Sep 10 '14 at 14:58

1 Answers1

6

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

Mohammad AbuShady
  • 40,884
  • 11
  • 78
  • 89