开发者

how to convert a fraction to float in ruby

开发者 https://www.devze.com 2022-12-19 22:27 出处:网络
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 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 开发者_如何学Golb", "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


Use Rational

>> (Rational(*("1/16".split('/').map( &:to_i )))*45).to_f
=> 2.8125


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


@Farrel was right, and since Ruby 1.9 includes Rational and String has a to_r-method things are easier:

puts ("1/16".to_r * 45).to_f  #=> 2.8125
puts ("1/16".to_r * 45).to_f.round(2) #=> 2.81

In 2.0 it became even easier with a rational literal:

1/16r # => (1/16)
0

精彩评论

暂无评论...
验证码 换一张
取 消