You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AppScript中将数字格式改为#,###,###?遇TypeError报错求助

问题解决:TypeError: String(...).setNumberFormat is not a function

错误原因

setNumberFormat是Google Sheets的Range对象方法,仅用于设置单元格的显示格式,并非JavaScript字符串的内置方法。你用String(row[7])将数字转为字符串后调用该方法,必然触发报错。

正确的数字格式化方法

需要将数字直接格式化为目标格式的字符串,再替换到文档中,以下两种方法均可实现需求:

方法1:使用Google Apps Script内置工具类Utilities.formatString

该方法可快速格式化数字,支持千分位和小数位数配置:

// 格式化为带千分位、保留3位小数的字符串(示例:1234567 → 1,234,567.000)
const osdNumberFormat = Utilities.formatString("%,.3f", row[7]);
  • %, 表示添加千分位分隔符
  • .3f 表示强制保留3位小数

方法2:使用JavaScript原生Intl.NumberFormat

若需要适配本地语言格式(比如印尼语区域规则),可使用该方法,默认会自动添加千分位:

// 指定印尼语区域,强制保留3位小数
const osdNumberFormat = new Intl.NumberFormat('id-ID', {
  minimumFractionDigits: 3,
  maximumFractionDigits: 3
}).format(row[7]);

修改后的核心代码片段

将你代码中错误的格式化语句替换为上述任意一种写法即可,修改后的核心部分示例:

// ... 其他代码保持不变
const friendlyDate = new Date(row[10]).toLocaleDateString();
const dueDateFormat = new Date(row[9]).toLocaleDateString();
// 替换为正确的格式化代码
const osdNumberFormat = Utilities.formatString("%,.3f", row[7]);

// 后续文本替换逻辑保持不变
body.replaceText('{{osd_num_amount}}', osdNumberFormat);
// ...

额外注意

如果row[7]是字符串类型,需先转为数字再格式化:

const osdNumberFormat = Utilities.formatString("%,.3f", Number(row[7]));

内容的提问来源于stack exchange,提问作者Yoza Tama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 20:42:43