Error with simple calculation in javascript

2

I'm having trouble making an account using javascript:

javascript

num1 = $("#num1").val(); // exemplo 2
num2 = $("#num2").val(); // exemplo 50

result = num1+num2;

This code results in 250 instead of 52

It looks like it's concatenating instead of adding.

How to fix this error?

    
asked by anonymous 24.03.2014 / 19:34

4 answers

1

you need to transform to integer for this use the function parseInt first for example:

num1 = parseInt($("#num1").val()); // exemplo 2
num2 = parseInt($("#num2").val()); // exemplo 50

result = num1+num2;
    
24.03.2014 / 19:36
7

You are by default javascript concatenated, because in val () it takes a string, to perform the sum you need to convert to numbers, which can be float (numbers with,) or int (integer only),

num1 = parseInt($("#num1").val()); // exemplo 2
num2 = parseFloat($("#num2").val()); // exemplo 50,4

result = num1+num2;
    
24.03.2014 / 19:42
6

The values are textual and not numeric. To receive exact values, whether floating or integer, you can use Number ():

result = Number(num1) + Number(num2)

Or you can use this solution too:

result = num1 * 1 + num2 * 1

In any case, if the text contains non-numeric characters, you must use parseInt (string) or parseFloat (string).

link

    
24.03.2014 / 19:54
5

You need to convert to number using for example parseInt ( ) .

In javascript the + sign in type string is to concatenate, in type number is to add.

The value you are receiving from .val() is string . Being a string the code thinks you want to join 50 after 2 and that's 250 .

Take a look here:

num1 = $("#num1").val(); 
num2 = parseInt($("#num2").val()); // usando o parseInt()
console.log(typeof num1); // string
console.log(typeof num2); // number

Example

    
24.03.2014 / 19:38