LoginSignup
0
2

More than 1 year has passed since last update.

金額をカンマ区切りで表示したい

Last updated at Posted at 2023-05-03

やりたい事

javascriptで、金額を3桁のカンマ区切りで表示したい!!

toLocaleString()を使う

toLocalesString()関数を使うことで簡単に実現できます。

数値.toLocaleString(locales, options);
 → localesやoptionsは指定せずとも使用可能です。
   その場合、既定のロケールと既定のオプションの整形された文字列が返されます。

日本語、ドイツ語、ロシア語などロケールの指定もでき、その数値を表す言語依存の文字列を返します。

let price = 10000;
price.toLocaleString();

console.log('¥', price);
// >>> ¥10,000

引数について

locales
localesを設定することで、指定したロケールに合わせた形に変換できます。

let price = 10000;

// アラビア語表記で表示
console.log(number.toLocaleString('ar-EG'));
// >>> ١٢٣٤٥٦٫٧٨٩

// インド語表記で表示(インド語では、thousands/lakh/croreの区切りを用いるようです)
console.log(number.toLocaleString('en-IN'));
// >>> 1,23,456.789

options
optionsを設定することで、返ってくる値をカスタマイズすることができます。

let price = 10000;

// ¥マークを付ける(styleにて「通貨」表示を指定、currencyにて通貨コードを指定)
console.log(price.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }))
// >>> ¥10,000

ブラウザ互換性

スクリーンショット 2023-05-05 5.39.22.png
Edgeでは、実装時に注意しなければならないようですが、それ以外のブラウザではしっかりサポートされているようなので、toLocalesString()は安心して使えそうです!
Mdn web docs - ブラウザ互換性

参考

Mdn web docs - Number.prototype.toLocaleString()
Mdn web docs - Intl.NumberFormat() コンストラクター

0
2
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
0
2