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;