Ruby - How to convert a mixed number to float?

I need to convert a mixed number to a float type, for example, from 1 1/2 to 1.5.

Is there a built-in method in ruby ​​to achieve the same?

+4
source share
2 answers

You can split into pieces, convert shapes to Rationals , summarize Rationals, and convert the result to Float:

s = '1 1/2' f = s.split.map { |r| Rational(r) }.inject(:+).to_f # 1.5 

If you know that a string will always contain two parts, you can process the fragments separately:

 s = '1 1/2' a = s.split f = a.first.to_i + Rational(a.last).to_f # 1.5 

If you are not sure how many parts will be (i.e. '1' , '3/2' , '11 23/42' , ... anything is possible), then the first should work in all cases.

Kernel # Rational will raise an ArgumentError if it cannot parse the string so you can wrap it all in begin / except to fix the errors.

+6
source
 s = '1 1/2' w, e, d = s.strip.match(/\A(\d+)?\s*(?:(\d+)\/(\d+))?\z/).to_a.drop(1).map(&:to_f) w + (e / d) # => 1.5 
0
source

Source: https://habr.com/ru/post/1386447/


All Articles