Do not add values

2

I'm trying to add two values, for example:

a = 400; b = 200;

I try to sum by means of "a + b", however instead of jQuery returning "600" it returns me "400200".

The actual code is this:

var startField = $dialogContent.find("input[name='newdate']").val();
var duracao = $dialogContent.find("input[name='duracao']").val();
console.log('final: ' + startField  + duracao * 60000);

What does it take to receive the sum of the values?

    
asked by anonymous 05.10.2014 / 00:30

3 answers

3

See:

console.log('final: ' + startField  + duracao * 60000);

The system will interpret as follows:

  • 'final' is a string then it will be concatenated with the variable startField, even if it is numeric.
  • The result of operation 1 will be a string, so it will also be concatenated with the result of operation length * 60000, since multiplication will be resolved before concatenation.
  • What you should do is use parentheses for the operation to be performed before concatenation with the "final" string:

    console.log('final: ' + (startField  + duracao * 60000) );
    

    Or use a variable to store the operation before concatenating:

    var total = startField  + duracao * 60000;
    console.log('final: ' + total );
    
        
    05.10.2014 / 00:50
    2

    You can force the conversion of your variables to numeric by making a sum that does not change the result of the variable, as in the examples below:

    var string = "10"; //retorna uma string
    var numero = string - 0; //devido ao cálculo - 0, retorna agora um numerico
    

    In addition to this, since JavaScript uses the + operator for both summing values and string concatenation, it is important that you separate the scope of your sum with parentheses, for example:

    console.log('final: ' + (startField  + duracao * 60000));
    

    Example: FIDDLE

        
    05.10.2014 / 00:41
    1

    Apparently I managed to resolve with "parseInt".

    var startField = $dialogContent.find("input[name='newdate']").val();
    var duracao = $dialogContent.find("input[name='duracao']").val();
    console.log('final: ' + (parseInt(startField) + parseInt(duracao) * 60000));
    
        
    05.10.2014 / 00:43