Ruby round float to_int if whole number
One simple way to it would be:
class Float def prettify to_i == self ? to_i : self endend
That's because:
irb> 1.0 == 1=> trueirb> 1 == 1.0=> true
Then you could do:
irb> 1.0.prettify=> 1irb> 1.5.prettify=> 1.5
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 endend
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.