Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 1200 to 1.2K in ruby/rails

I think there is a method within ruby or rails that does this but I can't remember where to find it or how to search for it, so I was hoping stackoverflow's collective wisdom might help. I don't mind writing a method to do this, but I'm sure someone has a better solution.

like image 932
b_d Avatar asked Jul 21 '11 11:07

b_d


2 Answers

number_to_human(1200, :format => '%n%u', :units => { :thousand => 'K' })

# 1200 => 1.2K
like image 121
Anatoly Avatar answered Oct 02 '22 15:10

Anatoly


If your number happens to be 1223 the accepted answer output would be 1.22K, include the precision parameter to reduce this to 1.2K. Also, if your number could be a wide range of numbers in the millions and billions, then best to cater for these also:

number_to_human(1200, :format => '%n%u', :precision => 2, :units => { :thousand => 'K', :million => 'M', :billion => 'B' })
# => "1.2K"

number_to_human(1223, :format => '%n%u', :precision => 2, :units => { :thousand => 'K', :million => 'M', :billion => 'B' })
# => "1.2K" 

number_to_human(1223456789, :format => '%n%u', :precision => 2, :units => { :thousand => 'K', :million => 'M', :billion => 'B' })
# => "1.2B" 
like image 24
joshweir Avatar answered Oct 02 '22 17:10

joshweir