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

121
Visualizações
Rounding Issue with Javascript using Math

I'm working on a project where I have an input field where a user puts in a dollar amount and depending on the frequency they would like to pay it divides that amount by said value (2, 4, or 12). So for instance if I put in an amount of $5 and had the frequency set at 2, I would have it display $2.50 for the charge amount. The issue I am having is if a user inputs $20.27 with frequency set at 2, I would expect to see $10.14 as the display but for some reason am getting $10.13 even after using Math.round and a toFixed(2). If I input $2.27 or $0.27 I do get the expected $1.14 and $.14 respectively but as soon as I get to more than $10 it no longer rounds correctly. I cannot figure out what I am doing wrong. Here is my code:

const setAmount = (num) => {
        scope.selectAmount(selectedAmount / num);
        finalAmount = ((Math.round(selectedAmount * 100) / 100) / num).toFixed(2);
        selectedAmountText = '$' + finalAmount;
        $('#pay-schedule span').text(selectedAmountText);

    }

Any help would be tremendously appreciated. Thanks!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Change the ordering as follows:

finalAmount = ((Math.round(selectedAmount / num * 100) / 100)).toFixed(2);

Dividing later messes things up.

about 4 years ago · Juan Pablo Isaza Relatório

0

I don't have an exact explanation for this but dividing by 2 at the end makes it somewhat inconsistent. So diving the number by 2 in the first place solves the issue for the specific values that you've provided.

function round(num) {
  let val = num / 2
  return (Math.round(val * 100) / 100).toFixed(2);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

I'm not sure why you need toFixed().

var amount=20.27;
var frequency=2;
var finalamount=amount/frequency;
finalamountrounded=Math.round(finalamount * 100) / 100
console.log(finalamountrounded)

produces

10.14
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