Rails: Is there a rails trick to adding commas to large numbers?

Ruby on-RailsRuby

Ruby on-Rails Problem Overview


Is there a way to have rails print out a number with commas in it?

For example, if I have a number 54000000.34, I can run <%= number.function %>, which would print out "54,000,000.34"

thanks!

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You want the number_with_delimiter method. For example:

<%= number_with_delimiter(@number, :delimiter => ',') %>

Alternatively, you can use the number_with_precision method to ensure that the number is always displayed with two decimal places of precision:

<%= number_with_precision(@number, :precision => 2, :delimiter => ',') %>

Solution 2 - Ruby on-Rails

For anyone not using rails:

number.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse

Solution 3 - Ruby on-Rails

The direct way to do this, with or without Rails, is:

require 'active_support'
require 'active_support/core_ext/numeric/conversions'

12345.to_s(:delimited)      # => "12,345"
12345.6789.to_s(:delimited) # => "12,345.6789"

For more options, see Active Support Core Extensions - Numeric - Formatting.

Solution 4 - Ruby on-Rails

Yes, use the NumberHelper. The method you are looking for is number_with_delimiter.

 number_with_delimiter(98765432.98, :delimiter => ",", :separator => ".")
 # => 98,765,432.98

Solution 5 - Ruby on-Rails

If you want to add commas outside of views and you don't want to include some modules, you can use number_to_delimited method (rails version >= 4.02). For example:

#inside anywhere
ActiveSupport::NumberHelper.number_to_delimited(1000000) # => "1,000,000"

Solution 6 - Ruby on-Rails

If you're doing it a lot but also FYI because it's not implied by the above, Rails has sensible defaults for the number_with_delimiter method.

#inside controller or view
number_with_delimiter(2444323.4)
#=> 2,444,323.30

#inside console
helper.number_with_delimiter(233423)
#=> 233,423

No need to supply the delimiter value if you're doing it the most typical way.

Solution 7 - Ruby on-Rails

A better way for those not using rails that handles decimals:

parts = number.to_s.split('.')
parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1,")
parts.join('.')

If you want a different delimiter, change the last ',' in the regex.

For bonus, this is how the regex is working:

  • gsub replaces everything that matches the regex with the second parameter passed to gsub. In this case that is \\1. \\1 becomes \1 when evaluated which matches the first capture group in the regex. In this regex that is (\d).
  • (\d)(?=(\d\d\d)+) is matching a digit followed by 1 or more groups of 3 digits. The first set of parens is our \1 capture group, the second would be \2. If we were just to leave it at that we would get: 123456.gsub!(/(\d)(?=(\d\d\d)+)/, "\\1,") #=> 1,2,3,456 This is because 1234 matches, 2345 matches and 3456 matches so we put a comma after the 1, the 2, and the 3.
  • By adding the (?!\d) we are matching anything that comes before that doesn't precede a digit so (\d)(?=(\d\d\d)+(?!\d)) means match a digit followed by 3 digits that is not followed by a digit. The reason why this works is that gsub will keep replacing things that match the string. If we were only going to replace the first match then for a number like 123456789 we would get 123456,789. Since 123456,789 still matches our regex we get 123,456,789.

Here is where I got the code: https://github.com/rails/rails/blob/master/activesupport/lib/active_support/number_helper.rb#L298-L300

And here is where I learned about what is going on in that regex: http://www.tutorialspoint.com/ruby/ruby_regular_expressions.htm

Solution 8 - Ruby on-Rails

You can use methods from ActiveSupport

For example:

ActiveSupport::NumberHelper::number_to_currency(10000.1234,{precision: 2,unit: ''})

Solution 9 - Ruby on-Rails

Another solution that does not use Helpers: format with 2 decimal places, and then replace . by ,

puts(("%.2f" % 2.5666).gsub('.',','))
>> 2,57

Solution 10 - Ruby on-Rails

  def add_commas(numstring)
    correct_idxs = (1..100).to_a.select{|n| n % 6 == 0}.map{|n| n - 1}
     numstring.reverse.chars.join(",").chars.select.with_index{|x, i| i.even? || correct_idxs.include?(i)}.join.reverse
  end

This was my way in ruby

Addition edit: Basically it adds all commas in between the numbers and only selects the ones where the index + 1 % 6

I figured the commas up to 100 was fine but if you want a super long number just make 100 a higher number

Solution 11 - Ruby on-Rails

new syntax

number_with_delimiter(@number, delimiter: ",")

If you you want to user delimeter for money then you can do

number_to_currency(@number)

this will add $ too. If you are using money gem then you can do

Money.new(@number,"USD").format

This will also put $.

number_with_delimiter

ruby money

number_to_currency

Solution 12 - Ruby on-Rails

The following do the trick for both delimiter and precision (API ref).

ActiveSupport::NumberHelper.number_to_rounded(1234.532, delimiter: ',', precision: 1) 
     

(or from views just number_to_rounded, no need for the prefix)

HTH

Solution 13 - Ruby on-Rails

I had this challenge when working on a Rails 6 application.

If the number is for the price of an item or has to do with currency, then you can use number_to_currency ActionView Helper

Here's how to do it:

number_to_currency("123456789")                      # => $123456789
number_to_currency(1234567890.50)                    # => $1,234,567,890.50
number_to_currency(1234567890.506)                   # => $1,234,567,890.51
number_to_currency(1234567890.506, precision: 3)     # => $1,234,567,890.506
number_to_currency(1234567890.506, locale: :fr)      # => 1 234 567 890,51 €
number_to_currency(1234567890.50, unit: '₦', delimiter: ',', precision: 0)    # => ₦1,234,567,890
number_to_currency(1234567890.50, unit: "R$", separator: ",", delimiter: "")  # => R$1234567890,50

You can read up more about it here in the Rails documentation: number_to_currency

That's all.

I hope this helps

Solution 14 - Ruby on-Rails

For Ruby guys: Formatting numbers (integers only) with a comma separator between every group of thousands.

number = 12345678
numStr1 = number.to_s.reverse.scan(/.{1,3}/).join(',').reverse
puts numStr1             # => 12,345,678

numStr2 = number.to_s.gsub(/\B(?=(...)*\b)/, ',')
puts numStr2             # => 12,345,678

Solution 15 - Ruby on-Rails

For Ruby Folks: functions can be created to set comma to large number integer.

def number_with_comma(numStr)
   return numStr.to_s.gsub(/\B(?=(...)*\b)/, ',')
end
a = number_with_comma 1234567
puts a   => 1,234,567

x = 9876543
y = number_with_comma x
puts y   => 9,876,543

Solution 16 - Ruby on-Rails

for javascript folks

function numberWithDelimiter(value) {
    return (value+"").split("").reverse().join("").replace(/(\d{3})(?=\d)/g, '$1,').split("").reverse().join("")
}

:)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJessView Question on Stackoverflow
Solution 1 - Ruby on-RailsJohn TopleyView Answer on Stackoverflow
Solution 2 - Ruby on-RailspguardiarioView Answer on Stackoverflow
Solution 3 - Ruby on-RailschocolateboyView Answer on Stackoverflow
Solution 4 - Ruby on-RailsPatrikAkerstrandView Answer on Stackoverflow
Solution 5 - Ruby on-RailsAleksander RyhlitskiView Answer on Stackoverflow
Solution 6 - Ruby on-RailscoloradoblueView Answer on Stackoverflow
Solution 7 - Ruby on-RailsfxfilmxfView Answer on Stackoverflow
Solution 8 - Ruby on-RailsLe Duc DuyView Answer on Stackoverflow
Solution 9 - Ruby on-RailsNino van HooffView Answer on Stackoverflow
Solution 10 - Ruby on-RailsJustin CoxView Answer on Stackoverflow
Solution 11 - Ruby on-RailsgsumkView Answer on Stackoverflow
Solution 12 - Ruby on-RailsHertzel GuinnessView Answer on Stackoverflow
Solution 13 - Ruby on-RailsPromise PrestonView Answer on Stackoverflow
Solution 14 - Ruby on-RailsMohiuddin Ahmad KhanView Answer on Stackoverflow
Solution 15 - Ruby on-RailsMohiuddin Ahmad KhanView Answer on Stackoverflow
Solution 16 - Ruby on-RailsaqmView Answer on Stackoverflow