/** * 金额中文大写(小程序副本)——与服务端 `server/src/utils/amountInWords.ts` **同算法、同输出**。 * * 为什么要副本:小程序是 CommonJS、跑在微信运行时里,无法直接 import 服务端的 TS; * 两侧一致性由 `server/tests/mpDeliveryNoteImage.test.ts` 的「逐字对拍」用例钉住 * (同一批边界值两侧输出必须完全相同),改动任一侧都会被测试拦下。 * * 口径(与送货单「合计金额:玖佰肆拾捌元整 948.00」一致): * · 四舍五入到分再换算;· 整数 0 也写「零元」;· 角分均 0 结尾「整」; * · 角 0 有分补「零」;· 跨节/节内跳零各补一个「零」;· 上限到「万亿」节。 */ const DIGITS = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']; const UNITS = ['', '拾', '佰', '仟']; const SECTIONS = ['', '万', '亿', '万亿']; function sectionToWords(section) { let out = ''; let zeroPending = false; let rest = section; let unitIdx = 0; while (rest > 0) { const digit = rest % 10; if (digit === 0) { if (out) zeroPending = true; } else { if (zeroPending) { out = '零' + out; zeroPending = false; } out = DIGITS[digit] + UNITS[unitIdx] + out; } unitIdx += 1; rest = Math.floor(rest / 10); } return out; } function integerToWords(intText) { const digits = String(intText).replace(/^0+/, ''); if (!digits) return ''; const sections = []; let rest = digits; while (rest.length > 0) { sections.push(Number(rest.slice(-4))); rest = rest.slice(0, -4); } let out = ''; for (let i = sections.length - 1; i >= 0; i -= 1) { const section = sections[i]; if (section === 0) { const lowerHasNonZero = sections.slice(0, i).some((value) => value > 0); if (out && lowerHasNonZero && !out.endsWith('零')) out += '零'; continue; } if (i < sections.length - 1 && section < 1000 && out && !out.endsWith('零')) out += '零'; out += sectionToWords(section) + SECTIONS[i]; } return out; } /** 金额 → 中文大写(传「元」,内部四舍五入到分;非有限数按 0) */ function amountInWords(amount) { const raw = Number(amount); const safe = Number.isFinite(raw) ? raw : 0; const negative = safe < 0; const cents = Math.round(Math.abs(safe) * 100); const yuan = Math.floor(cents / 100); const jiao = Math.floor((cents % 100) / 10); const fen = cents % 10; const yuanWords = integerToWords(String(yuan)) || '零'; let out; if (jiao === 0 && fen === 0) { out = yuanWords + '元整'; } else { out = yuanWords + '元'; if (jiao > 0) out += DIGITS[jiao] + '角'; else if (fen > 0) out += '零'; if (fen > 0) out += DIGITS[fen] + '分'; } return negative ? '负' + out : out; } module.exports = { amountInWords };