0
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 2020-07-21

111011101110"一一一〇一一一〇一一一〇" ではなく "千百十億千百十万千百十" とするタイプです。

toKanjiNumber.js

const kanjiNumeral = [
  // これ以上は Number.MAX_SAFE_INTEGER を超えるため考慮しない。
  [1000000000000, ""],
  [100000000, ""],
  [10000, ""],
  [1000, ""],
  [100, ""],
  [10, ""],
];

const kanjiDigits = ["", "", "", "", "", "", "", "", "", ""];

const kanjiRecursive = (value) => {
  let current = value;
  let str = "";

  kanjiNumeral.forEach(([base, char]) => {
    const num = Math.floor(current / base);

    if (!num) return;

    let recurredStr = kanjiRecursive(num);

    if ("千百十".includes(char) && recurredStr.endsWith("")) {
      recurredStr = str.substring(0, recurredStr.length - 1);
    }

    current -= num * base;

    str = `${str}${recurredStr}${char}`;
  });

  return `${str}${kanjiDigits[current]}`;
};

const toKanjiNumber = (value) => {
  let num = Number(value);

  if (num === 0) return "";

  let positive = true;

  if (num < 0) {
    positive = false;
    num = Math.abs(num);
  }

  const str = kanjiRecursive(num);

  return positive ? str : `-${str}`;
};

export default toKanjiNumber;
0
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
0
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?