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

前端 未结 14 1909
小鲜肉
小鲜肉 2020-12-07 08:19

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

相关标签:
14条回答
  • 2020-12-07 09:18

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

    puts(("%.2f" % 2.5666).gsub('.',','))
    >> 2,57
    
    0 讨论(0)
  • 2020-12-07 09:18

    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

    0 讨论(0)
提交回复
热议问题