Skip to content

Instantly share code, notes, and snippets.

@mattknox
Created May 3, 2011 03:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattknox/952769 to your computer and use it in GitHub Desktop.
Save mattknox/952769 to your computer and use it in GitHub Desktop.
Numeric#humanize makes numbers more readable.
class Numeric
SCALE_TO_WORD = Hash.new do |h, i|
" * 10^#{i * 3}"
end.merge({ 1 => " thousand",
2 => " million",
3 => " billion",
4 => " trillion"
})
# in my unscientific test, no one really found names beyond trillion useful.
def humanize(figures = 3)
scale = (Math.log10(self) / 3).floor
base = 1000 ** scale
suffix = SCALE_TO_WORD[scale.abs]
suffix = "#{suffix}ths" if scale < 1 && suffix
sprintf("%.#{ figures }G", self.to_f / base) + suffix.to_s
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment