制作一个html,输入数字,转换成相应的繁体中文指多少钱,其中包括角和分
时间: 2024-06-01 22:03:30 浏览: 66
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>数字转换成繁体中文金额</title>
</head>
<body>
<h1>数字转换成繁体中文金额</h1>
<form>
<label for="amount">请输入数字金额:</label>
<input type="number" id="amount" name="amount" min="0" step="0.01" required>
<button type="submit">转换</button>
</form>
<div id="result"></div>
<script>
function convertToChinese(amount) {
const digits = ["零", "壹", "貳", "參", "肆", "伍", "陸", "柒", "捌", "玖"];
const units = ["", "拾", "佰", "仟"];
const levels = ["", "萬", "億", "兆", "京", "垓"];
let integerPart = Math.floor(amount);
let decimalPart = Math.round((amount - integerPart) * 100);
let integerPartStr = integerPart.toString();
let decimalPartStr = decimalPart.toString();
let chineseStr = "";
// 处理整数部分
for (let i = 0; i < integerPartStr.length; i++) {
let digit = integerPartStr.charAt(i);
let unit = units[integerPartStr.length - i - 1];
let level = levels[Math.floor(i / 4)];
if (digit != "0") {
chineseStr += digits[digit] + unit + level;
} else if (chineseStr.charAt(chineseStr.length - 1) != digits[digit]) {
chineseStr += digits[digit];
}
}
// 处理小数部分
if (decimalPartStr == "0") {
chineseStr += "整";
} else {
let decimalDigit1 = decimalPartStr.charAt(0);
let decimalDigit2 = decimalPartStr.charAt(1);
if (decimalDigit1 != "0") {
chineseStr += digits[decimalDigit1] + "角";
}
if (decimalDigit2 != "0") {
chineseStr += digits[decimalDigit2] + "分";
}
}
return chineseStr;
}
const form = document.querySelector("form");
const resultDiv = document.querySelector("#result");
form.addEventListener("submit", function(event) {
event.preventDefault();
let amount = parseFloat(form.elements.amount.value);
let chineseStr = convertToChinese(amount);
resultDiv.textContent = chineseStr;
});
</script>
</body>
</html>
阅读全文