Ruby round float to_int if whole number

floating-point, int, ruby

Solution

This is the solution that ended up working the way I want it to:

class Float
  alias_method(:original_to_s, :to_s) unless method_defined?(:original_to_s)

  def is_whole?
    self % 1 == 0
  end

  def to_s
    self.is_whole? ? self.to_i.to_s : self.original_to_s
  end
end

This way I can update the `is_whole?` logic (I seems like tadman's is the most sophisticated) if needed, and it ensures that anywhere a Float outputs to a string (eg, in a form) it appears the way I want it to (ie, no zeros on the end).

Thanks to everybody for your ideas - they really helped.

Problem

In ruby, I want to convert a float to an int if it's a whole number. For example ``` a = 1.0 b = 2.5 a.to_int_if_whole # => 1 b.to_int_if_whole # => 2.5 ``` Basically I'm trying to avoid displaying ".0" on any number that doesn't have a decimal. I'm looking for an elegant (or built-in) way to do ``` def to_int_if_whole(float) (float % 1 == 0) ? float.to_i : float end ```

Original source