Float to_s hack for easy sprintf'ing
1. to_s override.
I really hate using sprintf, mainly because i always have to go online
and look up the syntax. I figured i could make that a little easier.
Now you can print floats with different precision as easily as:
4.123456.to_s(1) # => "4.1"
4.123456.to_s(3) # => "4.12"
4.123456.to_s(3) # => "4.123"
4.123456.to_s(4) # => "4.1235" (Note the auto rounding from 4.123456)
4.123456.to_s # => "4.123456"
class Float alias_method :orig_to_s, :to_s def to_s(arg = nil) if arg.nil? orig_to_s else sprintf("%.#{arg}f", self) end end end
I have packaged this and other useful hacks into a plugin at http://blog.djdossiers.com/articles/2007/03/31/new-rails-plugin-jakes-toolbox
Peace
--jake