3

I have used number_with_delimiter method for adding commas for numbers in an invoice in Ruby on Rails. But the number format resulted in 23,324,455 and not as 2,33,24,455 that is, Indian Rupees format.

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

I have to generate Invoice with amount in Rupees so the format should be xx,xx,xxx.00. Is it possible in Rails? How to accomplish it?

This can be done with JavaScript but the problem is, I have generated the invoice in PDF format using PDFKit gem which does not respond with JavaScript. I have used the required js code on loading the document.

$(document).ready(function(){
  $('.totalvalue').each(function(){
    value = $('.totalvalue').text();
    $('.totalvalue').html(
      (value+"").split("").reverse().join("").replace(/(\d{3})(?=\d)/g,        '$1,').split("").reverse().join("")
    )
  })
})
Stefan
  • 109,145
  • 14
  • 143
  • 218
Nandy
  • 57
  • 8

2 Answers2

5

You can use money gem, and specifically explore its formatting options.

Money.new(10000000, "INR").format(:symbol => false, 
                                  :south_asian_number_formatting => true)    
#=> "1,00,000.00"
Wand Maker
  • 18,476
  • 8
  • 53
  • 87
  • this works fine but as you have mentioned, when the amount is 10000000, it gives 1,00,000.00 but what I expect is 1,00,00,000.00 and also when it has decimal point like 123456.5 it gives 1,234.56 instead of 1,23,456.50 – Nandy May 27 '16 at 11:04
  • 2
    @Nandy That gem works with paise - so the value should be specified in paise, not in rupees. As per documentation, `Represents monetary values as integers, in cents. This avoids floating point rounding errors.` – Wand Maker May 27 '16 at 11:15
2

Not elegant, but works:

("%.2f" % 23324455).reverse.gsub(/(?<=.{6})(\d\d?)/, ',\1').reverse
# => "2,33,24,455.00"
Amadan
  • 191,408
  • 23
  • 240
  • 301