How to format a number 1000 as “1 000”

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

    So, this is pretty crazy and hackish, but it gets the job done...

    12500.to_s.split("").reverse.each_slice(3).map {|y| y.join("").reverse}.reverse.join(" ")
     => "12 500" 
    
    .to_s: convert to string
    .split(""): split into separate digits
    .reverse: reverse order
    .each_slice(3): peel of each three digits (working from back end due to reverse)
    .map {|y| y.join("").reverse}: map into an array for each three digits - join back together with no delimiter and reverse order back to original
    .reverse: reverse order of mapped array
    .join(" "): join mapped array back together with space delimiter
    

提交回复
热议问题