除以两个变量返回0

时间:2015-03-13 07:07:44

标签: ruby

当我设置ratio = needed / count这个功能有效但是我需要一个百分比所以当我把它设置为ratio = count / needed时理论上应该给出一个小数点,但是它返回0。我做错了吗?我需要它返回正确的数字来设置宽度百分比。

  def percent_bar(piece, options={})
    count = file.total_count
    needed = HD::Application.config.files_needed
    ratio = count / needed
    percent = ratio * 100
    s = "<div class='progress'>"
    s += "<div class='progress-bar' role='progressbar' aria-valuemax='#{needed}' aria-valuenow='#{count}' aria-valuemin='0' style='width: #{ratio}%;'>"
    s += "<span class='sr-only'>#{count} of #{needed}</span>"
    s += "</div>"
    s += "</div>"

    return s

  end

2 个答案:

答案 0 :(得分:2)

您要划分两个整数值,因此结果将始终为整数。

请改为:

count / needed.to_f

示例:

count = 1
needed = 2
count / needed
# => 0
count / needed.to_f # type conversion to float
# => 0.5

答案 1 :(得分:1)

这是因为正在执行整数除法。使用to_f转换为float

ratio = count/needed.to_f