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 prin
for javascript folks
function numberWithDelimiter(value) {
return (value+"").split("").reverse().join("").replace(/(\d{3})(?=\d)/g, '$1,').split("").reverse().join("")
}
:)
For anyone not using rails:
number.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse
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"
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
new syntax
number_with_delimeter(@number, delimeter: ",")
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
You can use methods from ActiveSupport
For example:
ActiveSupport::NumberHelper::number_to_currency(10000.1234,{precision: 2,unit: ''})