LoginSignup
16
10

More than 5 years have passed since last update.

Javascriptで数字のカンマ区切り表示メモ

Posted at

Javascriptで数字のカンマ区切り表示

正規表現

javascript
function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

stackoverflow

toLocaleString()を使用

一番簡単。
そのまま引数にロケールを指定すればOKです。
ただし、Safari/PC,モバイルブラウザではlocale指定は非対応なのでフロントエンドには向かない。
Node(サーバーで実行)なら特に問題ないでしょう。

javascript@firefox
> var num = 123456.1234;
> console.log(num.toLocaleString('ja-JP'))
123,456.123 // 1/1000未満を四捨五入するようです

> console.log(num.toLocaleString('en-US'))
123,456.123 // 1/1000未満を四捨五入するようです

> console.log(num.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }))
123,456 // 1円未満は四捨五入するようです(Nodeは1/1000を四捨五入)

> console.log(num.toLocaleString('ja-JP', { style: 'currency', currency: 'USD' }))
$123,456.12 // 1セント未満は四捨五入するようです(Nodeは1/1000を四捨五入)

> console.log(num.toLocaleString('ja-JP', { style: 'currency', currency: 'EUR' }))
123,456.12 // 1セント未満は四捨五入するようです(Nodeは1/1000を四捨五入)

NodeJSだと出力が若干異なりました。

MDN:Number.prototype.toLocaleString()

Other

ほかにもNumberFormatを使ったり、ごりごり書いてみたりと、いろんな方法がありますねー。

toLocaleStringとNumberFormatのブラウザ対応表からすると、toLocaleStringはNumberFormatを使っているのかな?
そんな気がします。

ブラウザ向けなら正規表現が無難かなー。
どうでしょう。

16
10
0

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
16
10