Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert a fraction to float in ruby

Tags:

ruby

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.

I am trying in script/console

>> "1/16".to_f
=> 1.0
>> "1/16".to_f*45
=> 45.0

how can i get the desired result of 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") %>

whenever user selects oz value then i want to multiply it to 45

so i do:

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
like image 787
ratan Avatar asked Feb 13 '10 23:02

ratan


1 Answers

Use Rational

>> (Rational(*("1/16".split('/').map( &:to_i )))*45).to_f
=> 2.8125
like image 81
Farrel Avatar answered Sep 22 '22 14:09

Farrel