Google跟踪代码管理器自定义javascript变量来计算购物车总价值

时间:2018-06-11 22:41:22

标签: javascript google-tag-manager

我正在尝试根据网站数据层中包含的数据计算购物车的价值。

​{
  event: 'checkout',
  ecommerce: {
    checkout: {
      actionField: {step: 1},
      products: [
        {
          name: 'Nude Fur Collar Quilted Puffer Jacket',
          id: 'Nude-JKT-6824',
          price: 39.99,
          quantity: 1,
          category: ['Clothing', 'Clothing/Jackets & Coats'],
          variant: [false, false]
        },
        {
          name: 'Black Side Stripe Knee Cut Jeans',
          id: 'JN-004',
          price: 19.99,
          quantity: 1,
          category: ['Clothing', 'Clothing/Jeans'],
          variant: [false, false]
        }
       ]
    }
  },
  gtm.uniqueEventId: 12
}

我使用以下脚本创建了一个自定义javascript变量,这是我之前关于堆栈溢出的问题here

Dinesh的脚本有效,但输出返回此数字

59.980000000000004

我希望它能够返回

59.98

这是Dinesh的代码

function(){
  var productList={{ecommerce}}.checkout.products;
  var totalAmount=0;
  for(var i=0;i<productList.length;i++)
  {
    totalAmount+=(productList[i].quantity)*(parseFloat(productList[i].price));
  }
  return totalAmount;
}

我如何修改它以正确的格式输出结果,带有两个小数位。感谢。

1 个答案:

答案 0 :(得分:0)

在返回totalAmount时尝试使用toFixed()方法。此方法在保持指定的decimal.so数时非常有用。使用toFixed(2)只返回2个小数位。

function(){
var productList={{ecommerce}}.checkout.products;
var totalAmount=0;
for(var i=0;i<productList.length;i++)
{
totalAmount+=(productList[i].quantity)*(parseFloat(productList[i].price));
}
return totalAmount.toFixed(2);
}
相关问题