Ruby 除以两个变量返回0
当我将其设置为Ruby 除以两个变量返回0,ruby,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
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
def百分比_条(件,选项={})
计数=文件总数\u计数
需要=HD::Application.config.files\u需要
比率=计数/需要
百分比=比率*100
s=“”
s+=“”
s+=“{needed}中的{count}”
s+=“”
s+=“”
返回s
结束
您正在除以两个整数值,因此结果将始终为整数
改为这样做:
count / needed.to_f
例如:
count = 1
needed = 2
count / needed
# => 0
count / needed.to_f # type conversion to float
# => 0.5
这是因为正在执行整数除法。使用
转换为float
ratio=count/needed。要了解变量类型及其对运算符的影响,请阅读。