Skip to content

Instantly share code, notes, and snippets.

@jphastings
Created May 22, 2009 20:18
Show Gist options
  • Save jphastings/116334 to your computer and use it in GitHub Desktop.
Save jphastings/116334 to your computer and use it in GitHub Desktop.
Allows a percentage to be used as a float, but shown as a percentage (to variable decimal places)
# Cheers Andrew http://www.ruby-forum.com/topic/187508
require 'delegate'
# Allows percentages to be inspected and stringified in human
# form "33.3%", but kept in a float format for mathmatics
class Percentage < DelegateClass(Float)
def to_s(decimalplaces = 0)
(((self * 10**(decimalplaces+2)).round)/10**decimalplaces).to_s+"%"
end
alias :inspect :to_s
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment