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

Apps Script成本估算表单:数字会计格式兼容文本及合计问题

解决成本估算表单的两个问题:会计格式显示与求和优化

一、实现成本栏的会计格式显示(兼容文本输入)

  • 核心逻辑:输入框失去焦点时,判断内容是否为有效数字,是则自动格式化为$1,000.00样式,非数字内容(如TBA、Note Only)保持原样
  • 修改后的HTML(新增onblur事件触发格式化):
<div class="input-field col s2">
   <input placeholder="Cost" id="devCost9" type="text" class="inputCost" onchange="calculateTotalPrice()" onblur="formatAsCurrency(this)">
</div>
  • 添加格式化函数到JS:
function formatAsCurrency(inputElement) {
  const inputValue = inputElement.value.trim();
  // 清除现有格式中的$和逗号,判断是否为有效数字
  const cleanedValue = inputValue.replace(/[$,]/g, '');
  if (!isNaN(cleanedValue) && cleanedValue !== '') {
    const number = parseFloat(cleanedValue);
    // 用Intl API格式化为USD会计格式
    inputElement.value = new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    }).format(number);
  }
  // 非数字内容不做处理,保留原始输入
}

二、优化总计求和功能

  • 修复原问题:parseInt会丢失小数精度,且无法识别带格式的数值(如$1,000.00)
  • 修改后的求和函数:
function calculateTotalPrice(){
  const costInputs = document.querySelectorAll(".inputCost");
  let total = 0;
  for(let i = 0; i < costInputs.length; i++){
    const inputValue = costInputs[i].value.trim();
    // 清除格式字符,转换为浮点数
    const cleanedValue = inputValue.replace(/[$,]/g, '');
    const num = parseFloat(cleanedValue);
    // 仅累加有效数字
    if (!isNaN(num) && isFinite(num)) {
      total += num;
    }
  }
  // 总计同样格式化为会计格式
  document.getElementById("PicExtPrice").value = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(total);
}

额外说明

  • 输入时可直接输入数字(如1234.56),失去焦点后自动转为$1,234.56;输入文本内容则保持不变
  • 求和时会自动过滤非数字输入,仅对有效数值累加,最终结果以会计格式展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:30:45