Error with simple calculation in javascript

Asked

Viewed 515 times

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 he’s concatenating instead of adding.

How to fix this mistake?

  • 4

    It returns 250 because it is assuming that you have two strings.

  • 1

    Whenever using parseint use (value, Radix), because in javascript numbers starting with 0 are of the octal type, so if the value of "#num1" and "#num2" is for example 03 and 05 it will do the sum in octal, to avoid vc should use parseInt($("#num1").val(), 10) :)

  • This is not an error the val() method of jQuery returns a String the javascript operator "+" serves both to add and to concatenate, I suggest you take a look at http://www.codecademy.com/

4 answers

7

You are by default the 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(integers only),

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

result = num1+num2;

6

5

You need to convert to number using for example the parseint().

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

The amount you are receiving from .val() is a string. Being a string the code thinks you want to join 50 after the 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

1


you need to turn into whole so use the function parseInt first for example:

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

result = num1+num2;
  • 7

    To be perfect the ideal would be to use parseInt($("#num2").val(), 10) because if the value is for example "07" + "05" it interprets as octal.

  • 7

    @Leandroamorim +1, although in this case it makes no difference... Better examples would be "010" (8) and "020" (16)

  • 2

    I would recommend Number because the rescued value can return something in float format.

Browser other questions tagged

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