Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda