Pergunta

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.

Foi útil?

Solução 2

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

Outras dicas

Two possible options:

The Float method takes its argument and converts it to a floating-point number, terminating the program with an error if that conversion fails.

(failure_and_run_count[:failure] / Float(failure_and_run_count[:run])) * 100.0

to_f: Converts the number to a Float. If the number doesn’t fit in a Float, the result is infinity.

(failure_and_run_count[:failure] / failure_and_run_count[:run].to_f) * 100.0
Float (failure_and_run_count[:failure])
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top