如何使用Google App Script在Google Docs中格式化美元货币
解决Google Docs中灵活格式化USD货币字段的问题
问题背景
我有一个包含16个字段的Google Sheet,这些字段会自动填充至Google Docs模板中。其中5个为货币字段,需要在Google Docs中以$USD格式展示,数字范围覆盖$xx.xx到$x,xxx,xxx.xx,之前使用Utilities.formatString("$%'.2f", row[10])的方案灵活性不足,需要更适配的格式化方法。
优化方案:使用Intl.NumberFormat实现灵活货币格式化
Intl.NumberFormat是JavaScript原生的国际化API,能自动处理千位分隔符、固定小数位数,完美适配不同量级的数字,比Utilities.formatString更通用灵活。我们可以封装一个复用函数,批量处理所有5个货币字段:
封装格式化函数
// 封装USD货币格式化函数 function formatUSD(amount) { // 处理空值或非数字的容错情况 if (amount === "" || isNaN(amount)) return "$0.00"; return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(amount); }
修改原有代码
将原代码中直接替换货币字段的部分,替换为调用上述格式化函数的方式,示例如下:
if (row[13] == 'SPA'){ const copySPA_CO = spaCOTemplate.makeCopy(`FY25_CO_${row[13]}-${row[4]}-${row[14]}`, destinationFolder); const docSPA_CO = DocumentApp.openById(copySPA_CO.getId()); const body = docSPA_CO.getBody(); const friendlyDate = new Date(row[6]).toLocaleDateString(); const friendlyDate2 = new Date(row[7]).toLocaleDateString(); // 填充基础字段 body.replaceText('{{CO_NUMBER_1}}', row[2]); body.replaceText('{{PO_NUMBER_1}}', row[3]); body.replaceText('{{CO_NUMBER_2}}', row[2]); body.replaceText('{{PO_NUMBER_2}}', row[3]); body.replaceText('{{SUPPLIER}}', row[4]); body.replaceText('{{SUPPLIER_ADDRESS}}', row[5]); body.replaceText('{{PO_START_DATE}}',friendlyDate); body.replaceText('{{PO_NUMBER_3}}', row[3]); body.replaceText('{{DESCRIPTION_OF_CHANGE}}', row[8]); body.replaceText('{{PO_END_DATE}}', friendlyDate2); // 格式化并填充货币字段 body.replaceText('{{CO_AMOUNT_1}}', formatUSD(row[10])); body.replaceText('{{PO_AMOUNT_1}}', formatUSD(row[9])); body.replaceText('{{PO_AMOUNT_NEW_1}}', formatUSD(row[11])); body.replaceText('{{CO_AMOUNT_2}}', formatUSD(row[10])); body.replaceText('{{PO_AMOUNT_NEW_2}}', formatUSD(row[11])); body.replaceText('{{PO_NUMBER_4}}', row[3]); docSPA_CO.saveAndClose(); const urlSPA_CO = docSPA_CO.getUrl(); sheet.getRange(index + 1,16).setValue(urlSPA_CO); } else { return; }
方案优势
- 自动适配量级:无论数字是两位数还是百万级,都会自动添加千位分隔符,严格遵循$USD标准格式
- 容错性强:内置空值、非数字的判断逻辑,避免格式化失败
- 复用性高:一个函数即可处理所有5个货币字段,减少重复代码
内容的提问来源于stack exchange,提问作者kenzie
相关产品推荐
相关产品推荐

