2015-03-13 56 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