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
@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)
This is the most understandable answer I can think of:
def toFloat(fract)
str = fract.to_s
parts = str.split("/")
numerator = parts[0].to_f
denominator = parts[1].to_f
return numerator / denominator
end
puts toFloat(3/4r) # 0.75
puts toFloat(2/3r) # 0.666666666666...
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
Use Rational
>> (Rational(*("1/16".split('/').map( &:to_i )))*45).to_f
=> 2.8125