5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Elixirで3桁以上の数を3桁カンマ区切りで表示する

Last updated at Posted at 2022-01-13

Elixirに数を3桁カンマ区切りで表示する関数ないかなぁ、ありそうな気がするんだけどなぁ。
と思いつつ探しても見つからないかったので正規表現で無理やりやってみました。

やりたい事

3桁以上の数を3桁カンマ区切りで表示する。
例:1234567 -> 1,234,567

作成したコード

input = "1234567"
Regex.replace(~r/(\d)(?=(\d\d\d)+(?!\d))/, input, "\\g{1},")

iex(1)> input = "1234567"
"1234567"
iex(2)> Regex.replace(~r/(\d)(?=(\d\d\d)+(?!\d))/, input, "\\g{1},")
"1,234,567"

JavaScriptだとtoLocaleString()とか言うのがあるらしいんだけどなぁ。

ちなみに

numberというライブラリをインストールすると
Number.Delimit.number_to_delimited/2という関数を使用して変換できるみたいです。
(試してはいない。)

参考

https://www.yoheim.net/blog.php?q=20190702
https://hexdocs.pm/elixir/1.13/Regex.html#replace/4
https://elixircasts.io/formatting-numbers
https://hexdocs.pm/number/Number.Delimit.html

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?