4
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.

JavaScriptで数字に日本語の桁(万・億・兆)を付ける

Last updated at Posted at 2021-05-29

数字に日本語の桁(万・億・兆)を付けられるJavaScriptのライブラリを探していたのですが、見つからなかったので関数を作りました。

例えば、10020004000001兆20億40万に変換する感じです。

実際に作った関数は以下になります。

const toJaNum = (num) => {
  if (typeof num === "number") {
    num = num.toString();
  }

  let prefix = "";

  if (num[0] === "-") {
    num = num.slice(1);
    prefix = "-";
  }

  return (
    prefix +
    num
      .slice(0, -12)
      .replace(/^0+/, "")
      .replace(/([0-9]+)/g, "$1兆") +
    num
      .slice(-12, -8)
      .replace(/^0+/, "")
      .replace(/([0-9]+)/g, "$1億") +
    num
      .slice(-8, -4)
      .replace(/^0+/, "")
      .replace(/([0-9]+)/g, "$1万") +
    num.substring(num.length - 4).replace(/^0+/, "")
  );
};

最後に

もっといい書き方や、同じことができるJSのライブラリをご存知であればコメントいただけると嬉しいです。

4
1
3

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
4
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?