How to format a number 1000 as “1 000”

前端 未结 12 1005
北海茫月
北海茫月 2020-12-14 06:19

I need a way to format numbers. I stored some numbers in my DB table, e.g. 12500, and would like to print them in this format 12 500 (so there is a

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

    Another way:

    12500.to_s.reverse().split(//).inject() {|x,i| (x.gsub(/ /,"").length % 3 == 0 ) ? x + " " + i : x + i}.reverse()
    

    You can always Open the Fixnum class and add this for convenience:

    module FormatNums
      def spaceify
        self.to_s.reverse().split(//).inject() {|x,i| (x.gsub(/ /,"").length % 3 == 0 ) ? x + " " + i : x + i}.reverse()
      end
    end
    
    class Fixnum
      include FormatNums
    end
    
    12500.spaceify # => "12 500"
    
    0 讨论(0)
  • 2020-12-14 07:08

    This is old but the fastest and most elegant way I could find to do this is:

    def r_delim(s, e)                                                               
      (a = e%1000) > 0 ? r_delim(s, e/1000) : return; s << a                        
    end
    
    r_delim([], 1234567).join(',')
    

    I'll try and add benchmarks at some point.

    0 讨论(0)
  • 2020-12-14 07:11

    All but one of the answers use n.to_s. @MrMorphe's does not, but he creates an array to be joined. Here's a way that uses neither Fixnum#to_s nor Array#join.

    def separate(n,c=' ')
      m = n
      str = ''
      loop do
        m,r = m.divmod(1000)
        return str.insert(0,"#{r}") if m.zero?
        str.insert(0,"#{c}#{"%03d" % r}")
      end
    end
    
    separate(1)       #=>         "1"
    separate(12)      #=>        "12"
    separate(123)     #=>       "123"
    separate(1234)    #=>     "1 234"
    separate(12045)   #=>    "12 045"
    separate(123456)  #=>   "123 456"
    separate(1234000) #=> "1 234 000"
    

    Hmmm. Is that column on the right tipping?

    Another way that uses to_s but not join:

    def separate(n, c=' ')
      str = n.to_s
      sz = str.size
      (3...sz).step(3) { |i| str.insert(sz-i, c) }
      str
    end
    
    0 讨论(0)
  • 2020-12-14 07:12

    I just stumbled on this thread while looking for a way to format a value as US currency. I took a slightly different approach to the regex solutions proposed:

    amt = 1234567890.12
    f_amt = format("$%.2f",amt)
    i = f_amt.index(".")
    while i > 4
      f_amt[i-3]=","+f_amt[i-3]
      i = f_amt.index(",")
    end
    
    f_amt
    => "$1,234,567,890.12"
    

    This could be parameterized for formatting other currencies.

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

    very simple:

    number_with_delimiter(12500, delimiter: " ")

    see: http://apidock.com/rails/ActionView/Helpers/NumberHelper/number_with_delimiter

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

    Activesupport uses this regexp (and no reverse reverse).

    10000000.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1 ") #=> "10 000 000"
    
    0 讨论(0)
提交回复
热议问题