Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

108
Vistas
Round off to two decimal places and get positive numbers

I have placed this code in GTM to capture values from the product array and two issues are faced, currently:

var aa_ck_items = [];
try{
    var aa_ck_products = analytics_dataLayer.ecommerce.purchase.products || [];

aa_ck_products.forEach(function(element) {
    var currentItem = {
        "unitPrice": Number(element.price) / Number(element.quantity) + Number(element.discount),
        "itemId": element.id,
        "quantity": Number(element.quantity),
        "discount": Number(element.discount),
    }
    aa_ck_items.push(currentItem);
});

}catch(e){}

Issues faced

  1. When the unitPrice value is sent it has many numbers after the decimal e.g 12.23000002 and I am looking to round it off to two decimal places. I know the two methods we can use Math.round() and .toFixed(). I am not sure how to implement it to the code above.

  2. The discount value sometimes comes as a negative number and it always needs to be positive. How do I do that?

Can someone please help? Thank you!

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

  1. Wrap it all and use .toFixed(2) like you suggested~

  2. Do you want to make negative numbers positive, or negative numbers 0?

  • If you want to make them positive, you can use Math.abs()
  • If you want it to be zero then you can implement a function to do so.

Given your code...


aa_ck_products.forEach(function(element) {
    var currentItem = {
        "unitPrice": (Number(element.price) / Number(element.quantity) + Number(element.discount)).toFixed(2),
        "itemId": element.id,
        "quantity": Number(element.quantity),
        "discount": Math.abs(Number(element.discount)),
  // OR "discount": (Number(element.discount) > 0) ? Number(element.discount) : 0,
    }
    aa_ck_items.push(currentItem);
});
about 4 years ago · Juan Pablo Isaza Denunciar

0

For 1. I am not sure how to implement it to the code above <--- simply enclose the computation within ( & ) and suffix .toFixed(2) (if you need to fix to 2 digits after decimal, for example).

For 2. How do I do that? <--- Math.abs()

Both the items above are shown (with comments) on below code sample.

let aa_ck_items = [];
try {
  const aa_ck_products = analytics_dataLayer.ecommerce.purchase.products || [];
  aa_ck_products.forEach(function(element) {
    const currentItem = {
      "unitPrice": (
        Number(element.price) / Number(element.quantity) + Number(element.discount)
      ).toFixed(2), // <<--- #1 from question, assuming 2 digits after decimal for .toFixed()
      "itemId": element.id,
      "quantity": Number(element.quantity),
      "discount": Math.abs( // <<--- #2 from question, using Math.abs()
        Number(element.discount)
      )
    }
    aa_ck_items.push(currentItem);
  });

} catch (e) {}

NOTE - The usage of var has been modified to let or const as appropriate.

Below is how I would probably write this code:

let aa_ck_items = [];
try {
  const aa_ck_products = analytics_dataLayer.ecommerce.purchase.products || [];
  aa_ck_items = aa_ck_products.map(
    ({price, quantity, discount, id}) => ({
      "unitPrice": (
          Number(price) / Number(quantity) + Number(discount)
        ).toFixed(2),
      "itemId": id,
      "quantity": Number(quantity),
      "discount": Math.abs(Number(discount))
    })
  );
} catch (e) {}

Thank you James for the suggestion in the comments.

about 4 years ago · Juan Pablo Isaza Denunciar

0

//to approximate a decimal number using fixed-point notation
let number = 123.456;
number.toFixed(2); //expected as: 123.45

//to get the module (positive side) of a number    
let negative_number = -10;
Math.abs(negative_number); //expected as: 10
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda