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

前端 未结 14 1910
小鲜肉
小鲜肉 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:05

    for javascript folks

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

    :)

    0 讨论(0)
  • 2020-12-07 09:08

    For anyone not using rails:

    number.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse
    
    0 讨论(0)
  • 2020-12-07 09:10

    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"
    
    0 讨论(0)
  • 2020-12-07 09:12
      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

    0 讨论(0)
  • 2020-12-07 09:13

    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

    0 讨论(0)
  • 2020-12-07 09:17

    You can use methods from ActiveSupport

    For example:

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

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