Calculation of percentage in javascript

Asked

Viewed 30 times

0

Hello!

I’m with a question of those about a discount calculation code in javascript, below follows the code

JS

function ValorMensal () {
    var mensalidade, desconto, descontofinal, precofinal;
    mensalidade = parseFloat(document.getElementById("CAMPO_27").value);
    desconto = parseFloat(document.getElementById("CAMPO_25").value);
    descontofinal = mensalidade * desconto / 100;
    precofinal = mensalidade - descontofinal;
    document.getElementById("CAMPO_18").value = precofinal;
}

What happens, I have 2 problems, I’m almost 3 weeks and I can’t solve

When I play only the value of the monthly fee field, it should theoretically appear in the monthly and final field, regardless of whether there is a discount, but to my surprise it appears exactly the same as the image below

inserir a descrição da imagem aqui

And my other question is about the question of "," and "."

When I calculate discount with, for example. 2314.50, it rounds and when I put 2314.50, it gives me the exact amount. Can anyone give me a light? From now on I’m beaten

  • 1

    A light: parseFloat('') returns NaN.

  • 1

    I think your answer is here: https://answall.com/a/437716/119788

  • Calculations shall be made using . for the numbers. For this you can make a parseFloat(document.getElementById("CAMPO_25").value.replace(',', '.')). You will need to make one if to check if the discount value is greater than 0, otherwise it will not make the logic to apply the discount. Since the discount value will be 0 if the user does not fill in, and this will make its final value also 0 after multiplying. Another good practice is to use more meaningful names for the fields, such as "discount", "tuition" or something like "CAMPO_X".

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.