2015-03-13 88 views
-2

当我设置为ratio = needed/count该函数可以工作,但我需要一个百分比,所以当我将它设置为ratio = count/needed时,理论上它应该返回一个小数点,但它返回0.我在做什么错误?我需要它返回正确的数字来设置宽度百分比。划分两个变量返回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 
+1

请阅读变量类型以及它们如何影响运营商。 – Almaron 2015-03-13 07:12:34

回答

2

您正在分割两个整数值,所以结果将始终为整数。

执行此代替:

count/needed.to_f 

实施例:

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

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

ratio = count/needed.to_f