Why are you concatenating instead of adding?

Asked

Viewed 1,301 times

4

My code is concatenating instead of adding. What is the error?

var cFinal = 0;
var cFabrica = prompt("Insira o valor de fabrica do veículo");
var comissao = 0.28 * cFabrica;
var imposto = 0.45 * cFabrica;
cFinal = cFabrica + comissao + imposto;
document.write("O valor final é: ", cFinal);
  • 4

    As a suggestion, study javascript typing and operations. Since the language is not strongly typed, errors like this are common.

3 answers

14


The problem is that the prompt() returns a string.

This is not noticeable in multiplication because Javascript tries to convert into numbers but when you start this concatenation with a string, the conversion is left to right and everything is left string.

Forehead typeof cFabrica and you’ll see that it does string.

The solution is to convert in number so there is no doubt/bugs.

var cFabrica = prompt("Insira o valor de fabrica do veículo");

// teste 1
console.log('cFabrica é do tipo:', typeof cFabrica);
var numerocFabrica = Number(cFabrica);

// teste 2
console.log('numerocFabrica é do tipo:', typeof numerocFabrica);

var comissao = 0.28 * cFabrica;
var imposto = 0.45 * cFabrica;
var cFinal = numerocFabrica + comissao + imposto;
console.log("O valor final é: ", cFinal);

  • I managed to solve was just to put a parseint before the prompt.

  • 1

    @Negowell o parseInt is a solution. But beware if you have number with decimal part because the parseInt only gives you whole.

  • 1

    @Negowell Glad you liked the answers! But the best way to thank those who helped you is to mark "accept" the best answer and vote for all who helped you. This way you make sure that whoever wrote the answer gets something in return, as well as making the site cleaner and more useful for everyone. Adding a new answer like this (which is not an answer to the question and should be removed) makes the site more confusing and can get in the way.

5

var cFinal = 0;
var cFabrica = prompt("Insira o valor de fabrica do veículo");
var comissao = 0.28 * cFabrica;
var imposto = 0.45 * cFabrica;
cFinal = parseFloat(cFabrica) + comissao + imposto;
document.write("O valor final é: ", cFinal);

The prompt returns a string, to sum, you need a string int, then using parseFlaot, can add up.

5

What happens is that the function prompt always returns a string, so for the final account to be a sum and no concatenation it is necessary to convert the return of the function prompt for float:

var cFinal = 0;
var cFabrica = parseFloat(prompt("Insira o valor de fabrica do veículo"));
var comissao = 0.28 * cFabrica;
var imposto = 0.45 * cFabrica;
cFinal = cFabrica + comissao + imposto;
document.write("O valor final é: ", cFinal);

Browser other questions tagged

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