水曜日, 8月 06, 2025

Let's start JavaScript 79 
HTMLでアラビア数字を漢数字に変換

たま〜に必要なので、ダラダラ作っていました。
HTMLでアラビア数字を漢数字に変換します。


変換する漢数字は上の右端を基準としました。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>漢数字変換</title>
<style>
body {
margin: 0;
padding: 0;
height: 100%;
font-family: serif;
background-color: black;
color: white;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 50vh;
text-align: center;
}
input {
padding: 5px;
font-size: 18px;
margin: 5px;
}
button {
padding: 0px;
font-size: 16px;
margin: 5px;
width: 60px;
height: 30px;
}
#result {
margin-top: 20px;
font-size: 32px;
font-weight: bold;
color: white;
}
</style>
</head>
<body>
<div class="container">
<h3>アラビア数字を漢数字に変換<br>
        Convert Arabic Numerals to Kanji Numerals</h3>
<input type="number" id="inputNumber"
        placeholder="数値を入力">
<button onclick="convertToKanji()">変換</button>
<div id="result"></div>
</div>

<script>
function convertToKanji() {
const num =
        parseInt(document.getElementById('inputNumber').value, 10);
const resultDiv = document.getElementById('result');

if (isNaN(num)) {
resultDiv.textContent = '数値を入力してください。';
return;
}

resultDiv.textContent = numberToKanji(num);
}

function numberToKanji(num) {
const kanjiDigits = ['零', '壱', '弐', '参', '肆', '伍', '陸', '漆', '捌', '玖'];
const kanjiUnits = ['', '拾', '佰', '阡'];
const kanjiBigUnits = ['', '萬', '億', '兆'];

if (num === 0) return kanjiDigits[0];

let result = '';
const numStr = num.toString();
const chunks = [];

// 4桁ごとに右から区切る
let temp = numStr;
while (temp.length > 0) {
const chunk = temp.slice(-4);
chunks.unshift(chunk.padStart(4, '0'));
temp = temp.slice(0, -4);
}

chunks.forEach((chunk, i) => {
let part = '';
for (let j = 0; j < 4; j++) {
const digit = parseInt(chunk[j]);
if (digit !== 0) {
if (!(digit === 1 && j ===
                0 && chunk.length === 4 && i === 0 && j !== 3)) {
part += kanjiDigits[digit];
}
part += kanjiUnits[3 - j];
}
}
if (part !== '') {
result += part + kanjiBigUnits[chunks.length - 1 - i];
}
});

return result;
}
</script>
</body>
</html>



実行直後の画面。アラビア数字を入力して[変換]をクリックッすれば・・・


漢数字を表示します。
アラビア数字を漢数字に変換は、説明しないとワカランチンですね(^o^)汗

12345647890
12億3456万7890
十2億3千4百5十6万7千8百9十
一十二億三千四百五十六万七千八百九十
壱拾弐億参阡肆佰伍拾陸萬漆阡捌佰玖拾