1、html页面
<!DOCTYPE html>
<html>
<head>
<title>金额转换为大写</title>
<script src="script.js"></script>
</head>
<body>
<h1>金额转换为大写</h1>
<label for="amount">请输入金额数:</label>
<input type="text" id="amount" placeholder="请输入金额数">
<button onclick="convertToChinese()">转换</button>
<p id="result"></p>
<script>
function convertToChinese() {
var amount = document.getElementById("amount").value;
amount = parseFloat(amount).toFixed(2); // 保留两位小数
var result = numberToRMBWords(amount);
document.getElementById("result").innerHTML = "大写金额为:" + result;
}
</script>
</body>
</html>
2、script.js
function numberToRMBWords(number) {
const units = ['', '万', '亿'];
const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
const unitsSmall = ['', '拾', '佰', '仟'];
const subUnits = ['分', '厘', '毫']; // 添加“厘”和“毫”单位
function convertChunk(chunk, isDecimal = false, decimalIndex = 0) {
let result = '';
let hasZero = false; // 用于跟踪是否已经有零
for (let i = 0; i < chunk.length; i++) {
let digit = parseInt(chunk[i]);
if (digit !== 0) {
if (hasZero) {
result += digits[0]; // 添加零
hasZero = false;
}
if (isDecimal) {
if (decimalIndex === 0) { // “分”位
result += digits[digit] + subUnits[decimalIndex];
} else if (decimalIndex === 1) { // “厘”位
result += digits[digit] + subUnits[decimalIndex] + '之';
} else if (decimalIndex === 2) { // “毫”位
result += digits[digit] + subUnits[decimalIndex];
}
} else {
result += digits[digit] + unitsSmall[chunk.length - 1 - i];
}
} else {
hasZero = true;
if (i < chunk.length - 1 && parseInt(chunk[i + 1]) !== 0) {
result += digits[0]; // 添加零
}
}
}
return result;
}
// 处理整数部分和小数部分
let parts = String(number).split('.');
let integerPart = parts[0];
let decimalPart = parts[1] ? parts[1] : '';
let numberStr = integerPart;
let chunks = [];
while (numberStr.length > 4) {
chunks.unshift(numberStr.slice(-4));
numberStr = numberStr.slice(0, -4);
}
chunks.unshift(numberStr);
let result = '';
for (let i = 0; i < chunks.length; i++) {
if (parseInt(chunks[i]) !== 0) {
result += convertChunk(chunks[i]) + units[chunks.length - 1 - i];
} else {
if (i < chunks.length - 1 && parseInt(chunks[i + 1]) !== 0) {
result += digits[0]; // 添加零
}
}
}
if (result.startsWith(digits[0])) { // 检查是否以“零”开始
result = result.substring(1);
}
if (decimalPart) { // 处理小数部分,如果有的话
let decimalChunks = [];
while (decimalPart.length > 3) { // 每三位进行分割,以支持到“毫”位
decimalChunks.unshift(decimalPart.slice(-3));
decimalPart = decimalPart.slice(0, -3);
}
decimalChunks.unshift(decimalPart);
for (let i = 0; i < decimalChunks.length; i++) {
if (parseInt(decimalChunks[i]) !== 0) {
result += '点' + convertChunk(decimalChunks[i], true, i); // 注意:这里支持到“毫”位。
} else {
if (i < decimalChunks.length - 1 && parseInt(decimalChunks[i + 1]) !== 0) {
result += digits[0]; // 添加零
}
}
}
}
return result + '圆整'; // 注意:这里的“圆整”是指整数部分,对于小数部分,已经用“点”代替了。
}