1
0

3桁以上の数字をカンマで区切りたい時はtoLocaleString()

Posted at

はじめに

みなさんは3桁以上の数字をカンマ(,)で区切りたいと思ったことはありますか?
私は頻繁にあります!

¥30650, 2030kg, 6792034回....読みづらくないですか?
¥30,650, 2,030kg, 6,792,034回とカンマを入れるだけで読みやすくなる。

以前はどうしていたか

以下のようなメソッドを作って使いまわしていました。

tsファイル
const addComma = (count: number) => {
  const s = String(count).split(".");
  let result = String(s[0]).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
  if (s.length > 1) {
    result += "." + s[1];
  }
  return result;
};
vueファイル
<script setup lang="ts">
const const = ref<number>(6792034)
</script>

<template>
.
.
<div>{{ addComma(count) }}</div>   // 出力値: 6,792,034
.
.
</template>

でもこんなメソッド作らなくてよかったんです。

vueファイル
<div>{{ count.toLocaleString() }}</div> // 出力値: 6,792,034

.toLocaleString()で3桁以上の数字をカンマ(,)で区切れました!!

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