1

在应用程序脚本中,我想获取格式化的“数字”字符串。输入是一个未格式化的数字。使用@slandau 发布的较早答案,我认为我已经通过修改他的代码找到了解决方案(请参阅代码片段)。它在 codepen 中有效,但在我使用应用程序脚本时无效。1. 有谁知道这里出了什么问题?2. 我注意到这段代码除了在输入以 .0 结尾的数字时有效,在这种情况下返回值也是 .0 但应该是 .00。我也需要一些帮助来解决这个问题。谢谢!

我试图寻找类型强制问题,但无法解决。我对编码相当陌生。

function commaFormatted(amount)
{
    var delimiter = ","; // replace comma if desired
    var a = amount.split('.', 2);
    var preD = a[1]/(Math.pow(10,a[1].length-2));
    var d = Math.round(preD);
    var i = parseInt(a[0]);
    if(isNaN(i)) { return ''; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while(n.length > 3)
    {
        var nn = n.substr(n.length-3);
        a.unshift(nn);
        n = n.substr(0,n.length-3);
    }
    if(n.length > 0) { a.unshift(n); }
    n = a.join(delimiter);
    if(d.length < 1) { amount = n; }
    else { amount = n + '.' + d; }
    amount = minus + amount;
    return amount;
}

console.log(commaFormatted('100000.3532'))

预期结果为 100,000.35。我在 codepen 的 IDE 中得到了这个,但在 GAS IDE 中停止在 .split() 方法 => 不是一个函数。将 var a 转换为字符串时 = 我在记录 var a 时没有得到 ["100000", "3532"]。相反,我得到 100000 并期待 3532。

4

1 回答 1

1

根据这个答案,您的函数可以重写为

function commaFormatted(amount)
{
  var inputAmount;
  if (typeof(amount) == 'string') {
    inputAmount = amount;
  } else if (typeof(amount) == 'float') {
    inputAmount = amount.toString();
  }
  //--- we expect the input amount is a String
  //    to make is easier, round the decimal part first
  var roundedAmount = parseFloat(amount).toFixed(2);
  //--- now split it and add the commas
  var parts = roundedAmount.split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return parts.join(".");
}

console.log(commaFormatted(100000.3532));
console.log(commaFormatted('1234567.3532'));

于 2019-01-22T18:12:02.893 回答