![](/img/trans.png)
[英]Custom Javascript variable in Google Tag Manager and dataLayer
[英]Google Tag Manager custom javascript variable to calculate the total cart value
我正在嘗試根據網站數據層中包含的數據來計算購物車的價值。
{
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變量與下面的腳本,我從以前的問題,得到了上堆棧溢出這里
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;
}
我如何修改它以正確的格式輸出結果,並保留兩位小數。 謝謝。
返回totalAmount時,請嘗試使用toFixed()方法。 此方法對於保留指定的小數位數很有用。因此使用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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.