Does not add values

Asked

Viewed 805 times

2

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

a = 400; b = 200;

I try the sum through "a + b", however instead of jQuery returning me "600" it returns me "400200".

The real 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 it takes to receive the sum of the values?

  • inserts your code into the question for analysis, jQuery is concatenating the values and not adding.

  • I put the excerpt of my code Philip

3 answers

3


Behold:

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

The system will interpret it as follows:

  1. 'final' is a string so it will be concatenated with the startField variable, even if it is numerical.
  2. The result of operation 1. will be a string, then it will also be concatenated with the result of the duration operation*60000, since the multiplication will be solved before concatenation.

What you should do is use parentheses so that the operation is performed before concatenation with the string "final":

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 );

2

You can force the conversion of your variables to numerical by performing 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, how Javascript uses the operator + for both sum of values and string concatenation, it is important that you separate the scope of your addition with parentheses, for example:

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

Example: FIDDLE

1

Apparently I managed to solve it 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));

Browser other questions tagged

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