Created
May 3, 2011 03:28
-
-
Save mattknox/952769 to your computer and use it in GitHub Desktop.
Numeric#humanize makes numbers more readable.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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