Google跟踪代码管理器自定义javascript变量来计算购物车总价值 [英] Google Tag Manager custom javascript variable to calculate the total cart value
问题描述
我正在尝试根据网站数据层中包含的数据来计算购物车的价值.
I'm trying to calculate the value of the shopping cart based on data contained in my websites datalayer.
{
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变量,该脚本变量是我从上一个关于堆栈溢出的问题中得到的
I have created a custom javascript variable with the following script, that i got from a previous question on stack overflow here
Dinesh的脚本有效,但是输出返回该数字
Dinesh's script works, but the output returns this number
59.980000000000004
我希望它退回
59.98
这是Dinesh的代码
Here is Dinesh's code
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;
}
我该如何修改它以正确的格式输出结果,并保留两位小数.谢谢.
How can i modify this to output the result in the correct format, with two decimal places. Thanks.
推荐答案
返回totalAmount时,请尝试使用toFixed()方法.此方法对于保留指定的小数位数很有用.因此使用toFixed(2)仅返回2个小数位.
try using toFixed() method when returning the totalAmount. This method is useful in keeping a specified number of decimal.so using toFixed(2) would return only 2 decimal places.
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);
}
这篇关于Google跟踪代码管理器自定义javascript变量来计算购物车总价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!