How to Sum Multiple GTM Data Layer Variables into One
Need a custom variable to help you manipulate your data layer for a marketing tag? Enter the custom javascript variable in GTM.
Have you ever come across a data layer that had just about every possible eCommerce order variable but it was missing the only one that you needed to implement for a marketing tag?
Let’s say this is an example of your data layer:
But you need a variable that is the grand total: Revenue (87) + Tax (7.73).
Enter the custom Javascript variable in Google Tag Manager.
If you aren’t able to add this grand total variable to the data layer yourself then you can use a custom Javascript variable to sum these for you.
Here’s what this looks like:
function() { return parseFloat({{Purchase - Revenue}}) + parseFloat({{Purchase - Tax}}); }
This is a simple function that converts the variables to a floating point number (parseFloat) and then allows you to sum (+) one or more variables together.
You can do the same for other math operations. Be sure to update with your own variables from GTM and test in preview mode first.
Hi, thanks for nice tutorial. But in cases when one variable is undefined, function show NaN. Any ideas how to fix it?
You can use “Set Default” option to 0
parseFloat({{Purchase – Revenue}}) – does it mean make float from variable Revenue from Purchase ?