Jess
Jess

Reputation: 3151

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

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!

Upvotes: 240

Views: 101343

Answers (16)

chocolateboy
chocolateboy

Reputation: 1816

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

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

123456.to_fs(:delimited)     # => "123,456"
123456.789.to_fs(:delimited) # => "123,456.789"

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

Upvotes: 69

Mohiuddin Ahmad Khan
Mohiuddin Ahmad Khan

Reputation: 27

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

Upvotes: 0

Mohiuddin Ahmad Khan
Mohiuddin Ahmad Khan

Reputation: 27

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

Upvotes: 2

gsumk
gsumk

Reputation: 891

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

Upvotes: 2

Hertzel Guinness
Hertzel Guinness

Reputation: 5940

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

Upvotes: 1

Promise Preston
Promise Preston

Reputation: 28800

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

Upvotes: 2

Justin Cox
Justin Cox

Reputation: 21

  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

Upvotes: 1

Aleksander Ryhlitski
Aleksander Ryhlitski

Reputation: 708

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"

Upvotes: 34

Nino van Hooff
Nino van Hooff

Reputation: 3893

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

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

Upvotes: 1

Le Duc Duy
Le Duc Duy

Reputation: 1881

You can use methods from ActiveSupport

For example:

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

Upvotes: 1

coloradoblue
coloradoblue

Reputation: 625

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.

Upvotes: 21

aqm
aqm

Reputation: 3034

for javascript folks

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

:)

Upvotes: -1

fxfilmxf
fxfilmxf

Reputation: 582

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

Upvotes: 19

pguardiario
pguardiario

Reputation: 54984

For anyone not using rails:

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

Upvotes: 156

PatrikAkerstrand
PatrikAkerstrand

Reputation: 45721

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

Upvotes: 32

John Topley
John Topley

Reputation: 115292

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 => ',') %>

Upvotes: 399

Related Questions