如何将分数转换为在 ruby 中浮动 [英] how to convert a fraction to float in ruby
本文介绍了如何将分数转换为在 ruby 中浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串 "1/16"
我想将它转换为浮点数并乘以 45
.但是,我没有得到想要的结果.
I have a string "1/16"
I want to convert it to float and multiply it by 45
. However, I dont get the desired results.
我正在脚本/控制台
>> "1/16".to_f
=> 1.0
>> "1/16".to_f*45
=> 45.0
我怎样才能得到 2.81
大图:我有一个这样的下拉菜单:
Bigger picture: I have a drop down like this:
<%=select_tag :volume, options_for_select(["", "1 g", "1/16 oz", "1/8 oz","1/4 oz",
"1/2 oz", "1 oz", "1/8 lb", "1/4 lb", "Single", "Multi 5" ], "N/A") %>
每当用户选择 oz
值时,我想将其乘以 45
whenever user selects oz
value then i want to multiply it to 45
所以我这样做:
first, *rest = params[:volume].to_s.split(/ /)
if rest.first=="oz"
@indprodprice = @prods.orig_price.to_i*first.to_f*28.3495
else
@indprodprice = @prods.orig_price.to_i*first.to_f*453.59237
end
推荐答案
看起来您将不得不自己解析分数.这适用于分数和整数,但不适用于混合数(即:1½ 不起作用.)
Looks like you're going to have to parse the fraction yourself. This will work on fractions and whole numbers, but not mixed numbers (ie: 1½ will not work.)
class String
def to_frac
numerator, denominator = split('/').map(&:to_f)
denominator ||= 1
numerator/denominator
end
end
"1/16".to_frac * 45
这篇关于如何将分数转换为在 ruby 中浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文