Why are you concatenating instead of adding?

4

My code is concatenating instead of adding. what would be my mistake?.

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);
    
asked by anonymous 30.08.2017 / 20:59

3 answers

14

The problem is that prompt() returns a string .

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

Test typeof cFabrica and you will see that it gives string .

The solution is to convert numbers so there are no doubts / 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);
    
30.08.2017 / 21:02
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 do the sum, needs a int , then using parseFlaot , can add.

    
30.08.2017 / 21:02
5

What happens is that the prompt function always returns a string, so for the final count to be a sum and not concatenation it is necessary to convert the return of the function prompt to 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);
    
30.08.2017 / 21:03