How to format a number 1000 as “1 000”

前端 未结 12 1191
北海茫月
北海茫月 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

    The official document suggests three different ways:

    1) Using lookbehind and lookahead (Requires oniguruma)

    12500.to_s.gsub(/(?<=\d)(?=(?:\d{3})+\z)/, ' ')
    # => "12 500"
    

    2) Using only lookahead. Identical to steenslag's answer.

    3) Using neither lookahead nor lookbehind

    s = 12500.to_s
    nil while s.sub!(/(.*\d)(\d{3})/, '\1 \2')
    s # => "12 500"
    

提交回复
热议问题