LoginSignup
5
5

More than 5 years have passed since last update.

数字にカンマを入れてフォーマット

Last updated at Posted at 2013-07-26

3桁ずつ数字の間に","を挟むには、

numberFormat = (n) -> (n + '').split('').reduceRight (x, y) -> if (x.length + 1) % 4 then y + x else y + ',' + x

とするのがシンプル?

numberFormat = (n) ->
  s = n + '';
  s = s.replace(/(\d+)(\d{3})/, '$1,$2') while /(\d+)(\d{3})/.test s;
  s

でも良いけど、ワンライナーにはならない。(そして、正規表現の方が少し早い)

どちらも、使い方は↓こんな感じ。

s = numberFormat 1234567 # "1,234,567"
5
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5