Search code examples
rubyfloating-pointintegercoercion

Is there a better way to coerce an integer to a floating point in Ruby besides .round(1)?


Just what the question says in the title. I have a pair of integers, I want to convert it to a floating point so that I can do floating point math on it (to get a nice percentage).

Right now my code looks like this.

(failure_and_run_count[:failure].round(1) / failure_and_run_count[:run].round(1)) * 100.0

Someone please tell me there is a nicer way to coerce the ints inside of failure_and_run_count to floating points.


Solution

  • There's the method to_f for the purpose:

    1.to_f # => 1.0
    1.to_f.class # => Float
    

    In your example:

    failure_and_run_count[:failure] / failure_and_run_count[:run].to_f * 100.0
    

    Only one operand needs to be explicitly coerced to Float since the other is automatically coerced when you call the / method.

    Pay attention because nasty things could happen:

    ''.to_f # => 0.0
    nil.to_f # => 0.0
    'foo'.to_f # => 0.0