NumberHelper converts numbers to formatted values in Rails

Ruby on Rails is well-known for creating magic just with simple methods, and sometimes their benefits are underrated. With NumberHelper, Rails turns numbers into specifically formatted values.

The following methods format a number into a string of specified data, for instance number_to_currency(number, options={}) creates currency values that can be wrapped through the options hash. The method uses the default user locale to format the currency unit and number formatting. However it can be customised, if necessary, through specifying the :locale constant or through a currency conversion library.

1
2
number_to_currency(123567.50) # => "$123,567.50"
number_to_currency(123567.50, locale: :es) # => "123 567,50 €"

Other options like :delimiter, :separator, and delimiter_pattern help setting custom delimiters and separators.

Number_helpers also come handy when needed to transform very large numbers into a format readable by humans.

1
2
3
4
5
6
7
8
number_to_human(10000000000) # => "10 Billion"
number_to_human(1.000001) # => "1"

# to include non-significant zeros after the decimal separator
number_to_human(1.000001, strip_insignificant_zeros: false) # => "1.0"

# to use custom unit quantities
number_to_human(200000, units: {  unit: 'm', thousand: 'km' }) #=> "200 km"

With this method, unformatted numbers in databases can be converted to neatly arranged phone numbers. US is used as the default region, :country_code and :area_code options should apply for international numbers.

1
number_to_phone(2223336699, country_code: 33, area_code: true) #=> "+33 (222) 333-66-99"

Read more about it in the ActiveSupport::NumberHelper documentation.