Ruby Divide总是在Rails Axlsx Export中返回Zero

时间:2014-09-10 14:41:07

标签: ruby-on-rails axlsx

我不能为我的生活弄清楚为什么划分不适用于这个Aslsx出口。我可以加,减,多,并且模数除法很好,但是当我尝试answer_number / question_number时,它总是出现为0.任何想法我做错了什么?

工作吐出answer_numberquestion_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

不起作用 - 吐出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

我还认为,当数字小于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 * 100]
        end
    end

1 个答案:

答案 0 :(得分:5)

由于两个数字都是整数,因此ruby正在进行整数除法,它会忽略剩余的分数,我猜你所有的分区都返回0到1之间的数字,所以答案总是为0,以避免这两个数字中的一个应该是一个浮点数,就像@mtm建议的那样,将to_f函数添加到任一数字