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.
number_to_human(1200, :format => '%n%u', :units => { :thousand => 'K' })
# 1200 => 1.2K
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With