Adding commas to a number

前端 未结 3 1930
挽巷
挽巷 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: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
    

提交回复
热议问题