Adding commas to a number

前端 未结 3 1901
挽巷
挽巷 2021-01-29 09:18

I\'m trying to make a number like 1234567 go to be 1,234,567, but need some help. My thoughts were that I could use a split with \\d{3} and then join a , to that. T

相关标签:
3条回答
  • 2021-01-29 09:32

    i dont know if ruby has already an option to format numbers but in regex you can do this

    /\G([+-]?\d+?)(?=(?:\d{3})++(?=\.\d++$|$))/g
    

    then replace with this

    \1,
    

    sample: http://regex101.com/r/bA9cV2

    0 讨论(0)
  • 2021-01-29 09:37

    I'd use Rails' ActiveSupport (even if I wasn't using Rails for the actual application), which also formats it properly for the current locale. If you aren't already using Rails, you'll need to install the gem:

    gem install activesupport
    

    Then, require it like this:

    require "active_support/core_ext"
    

    Then you can do:

    => ActiveSupport::NumberHelper.number_to_delimited(1234567)
    => "1,234,567"
    
    0 讨论(0)
  • 2021-01-29 09:46

    More precise code (handles integers only, as OP did not mention floats!):

    def group_digits(n)
      n.to_s.chars
       .reverse
       .each_slice(3)
       .map(&:join)
       .join(",")
       .reverse
    end
    
    0 讨论(0)
提交回复
热议问题