Convert 1200 to 1.2K in ruby/rails Convert 1200 to 1.2K in ruby/rails ruby ruby

Convert 1200 to 1.2K in ruby/rails


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" 


Take a look at Rails Number Helper, The method number_to_human_size might be what you need.