0

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.

Jazzepi
  • 5,259
  • 11
  • 55
  • 81

3 Answers3

3

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
David Robles
  • 9,477
  • 8
  • 37
  • 47
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
toro2k
  • 19,020
  • 7
  • 64
  • 71
  • So I was looking at the Integer class (http://ruby-doc.org/core-1.9.3/Integer.html) assuming that the to_f function would live there. Why do I need to look at Fixnum instead of Integer? – Jazzepi May 31 '13 at 14:59
  • 1
    @Jazzepi `Integer` is the (abstract) base class for both `Fixnum` (integers that fits a machine word) and `Bignum` (integer bigger then `Fixnum`s), the `to_f` method is defined in the subclasses. More info on Ruby numeric types [here](http://rubylearning.com/satishtalim/numbers_in_ruby.html). – toro2k May 31 '13 at 15:05
  • Thanks! That's a great answer. LAST QUESTION I PROMISE :) Is there any way to tell that Integer is the abstract class? I come from a Java background and I'm used to stuff like that being marked abstract. I realize now at the top of the Integer document it mentions that this class is an abstract class, but is there anything /other/ than that text that I should, or can, look for? – Jazzepi May 31 '13 at 16:11
  • 1
    In Ruby abstract classes are not explicitly marked as such. It's quite impossible to explain how them can be implemented in a comment, especially to someone with a Java background! :-) Here on SO you can find lot of great explanations. – toro2k May 31 '13 at 21:23
1
Float (failure_and_run_count[:failure])
Mike Pugh
  • 6,787
  • 2
  • 27
  • 25