views:

242

answers:

2

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
+4  A: 

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
EmFi
ratan
EmFi
+4  A: 

Use Rational

>> (Rational(*("1/16".split('/').map( &:to_i )))*45).to_f
=> 2.8125
Farrel
I'd use that as it keeps maximum precision until you convert to float.
hurikhan77