diff --git a/README.md b/README.md index d26f355..480d019 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ Being impressed with the awesomeness of jstip repository, I came up with the ide Please feel free to send us a pull request with your Rails tip to be published here. Any improvements or suggestions are more than welcome! # Tips list +- 29 - [Convert a number into human readable](https://github.com/JPMallow/rails_tips/blob/master/rails_tip/2016-07-20-human_readable_number.md) - 28 - [Support for left outer join in rails 5](https://github.com/logeshmallow/rails_tips/blob/master/rails_tip/2016-03-10-left_outer_join_in_Rails_5.md) - 27 - [Render partial from cache faster](https://github.com/logeshmallow/rails_tips/blob/master/rails_tip/2016-03-09-rendering_partial_from_cache_faster.md) - 26 - [Increase productivity with console tricks](https://github.com/logeshmallow/rails_tips/blob/master/rails_tip/2016-03-08-Increase_productivity_with_few_tricks.md) diff --git a/rails_tip/2016-07-20-human_readable_number.md b/rails_tip/2016-07-20-human_readable_number.md new file mode 100644 index 0000000..5cb9df2 --- /dev/null +++ b/rails_tip/2016-07-20-human_readable_number.md @@ -0,0 +1,52 @@ +--- +title: Convert a number into human readable +tip-number: 29 +tip-username: Jayaprakash +tip-username-profile: https://github.com/JPMallow +tip-description: To convert the number into human readable format, you can use number_to_human helper method in Rails - http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html + +--- + +To convert the integer numbers into human readable format. + +```ruby +number_to_human(123) # => "123" +number_to_human(1234) # => "1.23 Thousand" +number_to_human(12345) # => "12.3 Thousand" +number_to_human(1234567) # => "1.23 Million" +number_to_human(1234567890) # => "1.23 Billion" +number_to_human(1234567890123) # => "1.23 Trillion" +number_to_human(1234567890123456) # => "1.23 Quadrillion" +number_to_human(1234567890123456789) # => "1230 Quadrillion" +number_to_human(489939, precision: 2) # => "490 Thousand" +number_to_human(489939, precision: 4) # => "489.9 Thousand" +number_to_human(1234567, precision: 4, + significant: false) # => "1.2346 Million" +number_to_human(1234567, precision: 1, + separator: ',', + significant: false) # => "1,2 Million" + +number_to_human(500000000, precision: 5) # => "500 Million" +number_to_human(12345012345, significant: false) # => "12.345 Billion" +``` + +Non-significant zeros after the decimal separator are stripped out by default (set :strip_insignificant_zeros to false to change that): + +```ruby +number_to_human(12.0000) # => “12” +number_to_human(12.0000, precision: 4, strip_insignificant_zeros: false) # => “12.00” +``` + +### Troubleshooting + +If you receive the following error + +``` +NoMethodError: undefined method `number_to_human' for main:Object +``` + +include NumberHelper in your controller / views. + +```ruby +include ActionView::Helpers::NumberHelper +```